I’m confused as to what is causing this behavior in my program. I’m just trying to copy the contents of one char* array to another and instead of copying the element, but it’s concatenating the strings in a strange way. I’m doing something like this:
char* a[50];
char* b[50];
for(int n=0; n<x; n++){
a[n] = malloc(sizeof(char) * (1 + strlen(b[n])));
strcpy(a[n], b[n]);
}
Has anyone experienced this before? I can post my output if that helps.
Thanks.
A few issues:
You loop while
n < x. What isx? Ifx >= 50, you’ll run off the end of your arrays. Your loop condition needs to protect against this possibility.Also, remember that the memory returned by
mallocis uninitialized. It is good that you are allocating an extra byte for the NULL terminator. What you are missing is the code that actually sets the value of the NULL terminator. The consequence of this is that youra[]strings are most likely not NULL-terminated (the last character is whatever random garbage that was previously stored in that byte). When you try to print them out or use a string function likestrlenon it, you’ll read past the end of the string and into whatever happens to be sitting in the memory range that follows.