2

I'm learning to write a native extension and I noticed an odd occurrence. When I allocate a multidimensional array and access it like so: (excuse any messy C code and bad practices I might be using unless they're likely the cause of my error. My C is not-so-great)

int table[rows][cols]; //rows and cols are both > 1
memset(table, 0, sizeof(int) * rows * cols);

I get a segmentation fault if I do something like

table[rows-1][cols-1];

But If I allocate the table like so:

table = (int**)malloc(XLEN * sizeof(int *));
if (table == NULL) {
  ... error ...
}

for (i=0; i < XLEN; i++) {
  table[i] = (int*)malloc(YLEN * sizeof(int));
  if (table[i] == NULL) {
    ... error ...
  }
  memset(table[i], 0, sizeof(int) * YLEN);
}

Then everything works fine. Why might this be?

4

1 回答 1

1

Maybe problem in that the in first case you allocate an array on the stack?
If you will use a reference to this array outside of the function (after when a function returns) you will always get a segmentation fault.

Please give a small example of the use of your array and you'll get more useful advice.

于 2015-06-14T14:10:04.813 回答