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;
}
A 2D array can be dynamically allocated in C using a single pointer. This means that a memory block of size row*column*dataTypeSize is allocated using malloc and pointer arithmetic can be used to access the matrix elements.
dynamically allocated arrays To dynamically allocate space, use calls to malloc passing in the total number of bytes to allocate (always use the sizeof to get the size of a specific type). A single call to malloc allocates a contiguous chunk of heap space of the passed size.
A 2D array is stored in the computer's memory one row following another. The address of the first byte of memory is considered as the memory location of the entire 2D array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With