Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically allocated string arrays in C

Tags:

arrays

c

malloc

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?


1 Answers

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.

like image 125
MooseBoys Avatar answered Dec 09 '25 23:12

MooseBoys