1

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]);
wasp256
  • 5,943
  • 12
  • 72
  • 119
  • [Dont cast the result of malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – OlivierLi Feb 19 '14 at 20:54

3 Answers3

4

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

Fvirtman
  • 161
  • 1
  • 4
1

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);
OlivierLi
  • 2,798
  • 1
  • 23
  • 30
0

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.

Dabo
  • 2,371
  • 2
  • 18
  • 26