0

I am getting segmentation fault whenever I do this. I wonder if there is a way for me to assign a value to the struct without getting SegFault?

typedef struct _chunk
{
  int lo;       // lower bound
  int hi;       // higher bound
} chunk;

chunk_stack = (chunk **)malloc(10 * 10 * sizeof(chunk **));

for (i = 0; i < chunk_per_thread; i++)
{
   chunk_stack[myid][i].lo = 0;
   chunk_stack[myid][i].hi = 1;
}
  • 2
    You allocate memory for the first dimension, but not for the second. Do `chunk_stack[myid] = malloc(...);` too. – Olaf Dietsche Mar 27 '21 at 21:04
  • Does this answer your question? [Correctly allocating multi-dimensional arrays](https://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays) – kaylum Mar 27 '21 at 21:06

1 Answers1

2

Suppose you need to allocate a 2D array of size r * c.
You need to first allocate memory for the double pointer which you did but have an error in it i.e., one extra * inside malloc function.

chunk **chunk_stack = (chunk **)malloc(r * sizeof(chunk *));

Then you need to allocate memory for each of the rows separately.

for(int i = 0; i < r; i++){
    chunk_stack[i] = (chunk*)malloc(c * sizeof(chunk));
}
risingStark
  • 1,153
  • 10
  • 17
  • Correct but casting pointers is not recommended in C. See: https://stackoverflow.com/a/17260868/3808573 . Better to write `chunk **chunk_stack = malloc(r * sizeof(chunk *));` and `chunk_stack[i] = malloc(c * sizeof(chunk));` – ssd Mar 27 '21 at 21:35
  • @ssd Thanks. I didn't know about it. – risingStark Mar 27 '21 at 21:36