Reputation: 1687
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?
Upvotes: 0
Views: 79
Reputation: 31409
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.
Upvotes: 2
Reputation: 16876
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.
Upvotes: 1
Reputation: 35154
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 malloc
ed memory once statement strings[0]="AAA"
has been executed.
To copy the contents into the malloc
ed memory, write strcpy(strings[0],"AAA")
. Then the free
should be no problem any more.
Upvotes: 4