Hi there.
I'm writing a C program which takes n
strings and concatenates them using strcat.
First I alloc'd the target string at sizeof(char)*
the strlen of every string + 1 (for the null character). Then with a for I use strncat to create the final string.
At the and, I am appending the null character.
Everything goes fine, but sometimes, at the beginning of the target string, there are some strange characters (for example, a '?'). This happens when, during the execution of the program, the final string is shorter than before (during the same execution).
Is there something I am missing?
This is the code:
size = 0;
for(i = 0; i < n; i++) {
size += sizeof(char)*(strlen(strings[i]));
}
size++;
target = malloc(size);
if(!target) { /** Error handling... */ }
for(i = 0; i < n; i++) {
target = strncat(target, strings[i], strlen(strings[i]));
}
target[size] = '\0';
Thanks,
—Donovan