0

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.

Salih Erikci
  • 5,076
  • 12
  • 39
  • 69

2 Answers2

4

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

Community
  • 1
  • 1
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
1

You have only allocated one dimension of your 2d array.

This is how you can allocate the second dimension:

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

Or access it using some multiplication:

int* worker_table = calloc(number_of_workers*2,(sizeof(int)));
my_customer = worker_table[x + y * number_of_workers];
Pubby
  • 51,882
  • 13
  • 139
  • 180