0

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?

klutt
  • 30,332
  • 17
  • 55
  • 95
anurag86
  • 1,635
  • 1
  • 16
  • 31

3 Answers3

4

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.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
2

It would crash simply because it's what (usually, the behavior is undefined) happens when you try to free a pointer that is not pointing at memory that can be freed. Read more about string literals here: https://stackoverflow.com/a/1704433/6699433

And both of your examples are very badly written, since the malloc is simply never used.

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

is equivalent to

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

and

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

is equivalent to

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

Note that "equivalent" is not 100% correct, since you have side effects. I just wanted to show that some lines are completely pointless since you don't use result before reassigning the variables.

klutt
  • 30,332
  • 17
  • 55
  • 95
1
strings[0]=malloc(100);

Here strings[0] is a pointer to newly allocated memory. Then, however, you do strings[0]="AAA"; which causes it to point to "AAA", a string in read-only memory. Your allocated memory is now leaked. Then you try to free the "AAA", which you can't do because that's read-only memory.

In the first snippet it works because you release the duped memory, but you're still leaking the malloc allocated memory.

Blaze
  • 16,736
  • 2
  • 25
  • 44