1

I'm trying to declare an square matrix but I'm getting segfaults with values bigger than 1446 for rows/columns. I've found this value doing an "manual binary search".

Here's a snippet of my code:

boolean matrix[vertex][vertex];
memset(matrix, 0, sizeof(matrizAdjacencia[0][0]) * vertex * vertex);

The original run was trying to declare 32768*32768 positions. But it failed and then I started fixing low values until I found this 1446 value. The code fails before memset();

The boolean type is just an

typedef enum {true, false} boolean;

When running the program with gdb attached, the error generated is:

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_PROTECTION_FAILURE at address: 0x00007fff5f3ff548
0x00007fff8e6a5fba in tzload ()

Thanks in advance,

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
  • `enum` variables are likely to correspond to `int`. Might have better luck with `char` (which can certainly hold all the values of that enum). 1446*1446*4 = over 8 megabytes. – luser droog Sep 16 '13 at 11:23
  • 1
    Don't define your own `bool` type if possible, use `stdbool.h` instead . Your current type likely has `true==0` and `false==1` which WILL cause problems in the future. – user694733 Sep 16 '13 at 11:35
  • I'm doing static allocation only due academic purposes. I know that dynamic allocation of memory is way better than this... Thanks for the stdbool.h tip. I will check this. – Vinícius Ferrão Sep 16 '13 at 11:41

1 Answers1

3

This is possibly due to the stack size limit in the system. See ulimit -s which in most systems of 8MB.

So, 1446 * 1446 * 4 is nearly 8MB since enum takes size of int. So, you are not able to allocate more than the allowed stack size. The actual needed memory is 32768 * 32768 * 4 is nearly 4GB. You can probably use a bitmap, since you are dealing with boolean which reduces the needed memory. First changing the int to char reduces to 4GB / 4 = 1GB and from char to bit field reduces to 1GB / 8 = 128MB

Prefer using malloc or calloc for larger chunks of memory.

Sakthi Kumar
  • 3,047
  • 15
  • 28
  • This should be the problem. I can confirm that max stack size is 8MB in my OS X system. I'm only using static matrix due academic purposes. So I just need to use an bitmap to allocate this portion of data? – Vinícius Ferrão Sep 16 '13 at 11:45
  • 1
    Yes probably a `char[req_size]`. And u can use `malloc` or `calloc`. And each `char` represents 8 values. – Sakthi Kumar Sep 16 '13 at 11:50
  • Can you recommend some documentation about bitmap implementations? I've never used this approach. – Vinícius Ferrão Sep 16 '13 at 13:55
  • Hope these SO questions help http://stackoverflow.com/questions/2384016/how-to-put-bits-into-a-character-array http://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c – Sakthi Kumar Sep 16 '13 at 14:39