Reputation: 6242
Can somebody please explain me way the free(test[0])
is giving me a segmentation fault (core dumped)
? I've tried to comment out the free and then the program terminates correctly (except from the lost memory). Also if I comment out test[0] = "abcd"
and insert the free(...)
again it terminates correctly too!?
char **test = (char**) (malloc(sizeof(char*) * 5));
for (int i=0; i<5; i++) {
test[i] = (char*) (malloc(sizeof(char*) * 5));
}
test[0] = "abcd";
free(test[0]);
Upvotes: 1
Views: 419
Reputation: 2373
You overwrite your pointer test[0]
with address of "abcd"
,which is statically allocated array that resides in read-only area. Add this printf("%p",test[0]);
before and after test[0] = "abcd";
for visualisation of what happens.
Upvotes: 0
Reputation: 2846
Please see @Fvirtman's answer to fix your crash.
Then to prevent leaks :
test is a two dimentional array so you need to free each one of it's sub-arrays first then free test like this :
for (int i=0; i<5; i++) {
free(test[i]);
}
free(test);
Upvotes: 1
Reputation: 161
Use strcpy instead of == , because here, you just gives test[0] the adresse of a static chain "abcd", that cannot be disallocated like that.
Upvotes: 4