C - 2D Array malloc/free - Segmentation fault -


i have simple snippet below trying figure out reason getting segmentation fault.

int main (int argc, char** argv) {     const int size = 2;     char** test1 = null;     int index = 0;      test1=(char**)malloc(sizeof(char*) * size);     if (test1 != null)     {             (index = 0; index < size ; index++)             {                     test1[index]=(char*)malloc(sizeof(char));                     test1[index]='a';             }              //removing block not result in seg fault - start             (index = 0 ; index < size ; index++)             {                     free(test1[index]); //seg. fault here             }             //removing block not result in seg fault - end              free(test1);     }     return 0; } 

if remove block enclosed within start , end comment - not see seg fault. think result in leak.

any appreciated.

i think meant dereference test1[index]. code overwrites address of allocated memory 'a', hence when tries free memory segs fault because 'a' not valid address.

test1[index]=(char*)malloc(sizeof(char)); *test1[index]='a'; 

this works well

test1[index][0]='a'; 

Popular posts from this blog