I would like to submit my enhanced concatenating function for your review. Originally, its method signature is:
char *concat (const *char1, const *char2);
but after knowing that the calling code must supply all the arguments when it calls the function, I modified the method signature to:
char *enhconcat (const char *str1, int start_index1, int end_index1, const char *str2, int start_index2, int end_index2);
supplying the necessary positional arguments, so I think the code is more secured and adaptable to future changes.
Please suggest ways to improve this code and make it more secure.
/* enhconcat.c: enhanced concat - for more secured concatenating */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *
enhconcat (const char *str1, int start_index1, int end_index1,
const char *str2, int start_index2, int end_index2);
int main (void) {
const char *part1 = "Cuius est solum, ";
const char *part2 = "eius est usque ad coelum et ad inferos.";
printf ("%s\n", enhconcat (part1, 0, strlen (part1), part2, 0, strlen (part2)));
return (EXIT_SUCCESS);
}
char *
enhconcat (const char *str1, int start_index1, int end_index1,
const char *str2, int start_index2, int end_index2)
{
int m = end_index1 - start_index1;
int n = end_index2 - start_index2;
char *concatstr;
concatstr = malloc (m + n + 1);
if (!concatstr) {
printf ("Unable to allocate memory.\n");
exit (EXIT_FAILURE);
}
char *chrptr;
chrptr = concatstr; // store address of concatstr
for (int i = start_index1; i < m; i++) {
*chrptr = str1[i];
chrptr++;
}
for (int j = start_index2; j < n; j++) {
*chrptr = str2[j];
chrptr++;
}
*chrptr = '\0';
return concatstr;
} /* end of enhconcat() */