Search code examples
cmemory-managementmultidimensional-arraydynamic-arrays

Memory allocation for 2D array in C


I am writing a multithreaded C program and I have an error. I have a 2D array array worker_table declared globally as:

int **worker_table;

And allocated in main as follows:

worker_table        = (int**) calloc(number_of_workers*2,(sizeof(int)));

This is the worker function:

    void *Worker(void *worker_id)
    {

my_id = (int)worker_id;    //id of the worker
printf("Line 231\n");
printf("My id is %d\n",my_id);
my_customer = worker_table[my_id][1];//line 233
printf("Line 234\n");
int my id;

The error happens before line 234, I think what is wrong is on line 233, but I can't figure out what it is.


Solution

  • Your allocation is wrong. It should be like this:

    worker_table = calloc(number_of_workers,(sizeof(int*)));
    for(int i = 0; i < 2; ++i)
    {
       worker_table[i] = calloc(2, sizeof(int));
    }
    

    And the freeing procedure should be:

    for(int i = 0; i < 2; ++i)
    {
        free(worker_table[i]);
    }
    free(worker_table);
    

    I suggest that you should read a good book on C