I'm trying to understand how dynamically allocated arrays work in C 99. Anyways, I have the following code:
int main()
{
char** members=malloc(4*sizeof(*members));
*members=malloc(5);
*members="john";
*(members+1)="shouldn't work";
printf("%s \n",*members);
printf("%s",*(members+1));
return 0;
}
I thought I would get a run time error because I didn't allocate (members+1), but actually it did print both "john" and "shouldn't work", Also, it apperas the the *members=malloc(5) line wasn't necessary. Why?
Your assignments aren't doing what you think they're doing. When you assign *members or *(members+1), you're assigning the char* to each string literal, not copying it to allocated (or not allocated) heap memory.
If instead you replaced your assignments with strcpy, i.e.:
strcpy(*members, "john");
strcpy(*(members+1), "shouldn't work");
Then you will get an access violation on the second assignment but not the first. Likewise, the reason malloc(5) appears to be unnecessary is because you reassign the pointer to point to the string literal, instead of copying the "john" string to the allocated memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With