Search code examples
cfreestrdup

free'ing results in crash


What is the difference between:

Case1:

    char* strings[100];
    strings[0]=malloc(100);
    char str[100]="AAA";
    strings[0]=strdup(str);
    free(strings[0]);

Case2:

    char* strings[100];
    strings[0]=malloc(100);
    strings[0]="AAA";
    free(strings[0]);

Case2 results in a crash. strdup is as good as malloc followed by strcpy. Why should second case crash?


Solution

  • strings[0]="AAA"; does not copy the contents AAA into the memory to which string[0] points, it rather lets strings[0] point to string literal "AAAA"; and freeing a string literal is undefined behaviour, since you are freeing memory which has not been allocated through malloc before. Note that you lost any access to your previously malloced memory once statement strings[0]="AAA" has been executed.

    To copy the contents into the malloced memory, write strcpy(strings[0],"AAA"). Then the free should be no problem any more.