Question

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]);
Was it helpful?

Solution

Use strcpy instead of == , because here, you just gives test[0] the adresse of a static chain "abcd", that cannot be disallocated like that.

OTHER TIPS

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);

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top