Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically allocating memory for 2d char array

Tags:

c

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;
}
like image 272
Joe K Avatar asked Jan 17 '19 21:01

Joe K


People also ask

Can we allocate a 2 dimensional array dynamically?

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.

Can we use dynamic memory allocation in array?

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.

How 2D array is stored in memory?

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.


1 Answers

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.

like image 71
dbush Avatar answered Nov 05 '22 23:11

dbush