Dynamically allocating memory for 2d char array

  • A+
Category:Languages

I am using malloc to dynamically allocate a 2d char array. Unless I set every array index to NULL before free(), I get a segmentation fault when trying to free(). Why do I get a segmentation fault?

#include <stdio.h> #include <stdlib.h>  int main(void) {      int nrows = 20; int ncolumns = 10;     char ** arr = malloc(nrows * sizeof(char *));     for(int i = 0; i < nrows; i++)         arr[i] = malloc(ncolumns * sizeof(char));      arr[0] = "string1";     arr[1] = "string2";      // does not work without the following code:     // for(int i = 0; i < 20; i++)     //     arr[i] = NULL;      for(int i = 0; i < 20; i++)         free(arr[i]);     free(arr);      return 0; } 

 


When you do this:

arr[0] = "string1"; arr[1] = "string2"; 

You overwrite the contents of arr[0] and arr[1], which contain the addresses of memory returned from malloc, with the address of two string constants. This causes a memory leak, as that memory is no longer accessible. This is also the reason you crash when you call free because these variables no longer hold the addresses of allocated memory.

What you probably want to do here instead is use strcpy, which will copy the contents of the string literal to the memory you allocated.

strcpy(arr[0], "string1"); strcpy(arr[1], "string2"); 

Now you can free the memory properly.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: