Question

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,

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top