Search code examples
segmentation-faultmallocallocation

Why does "segmentation fault" occur in this case


in this case occur "segmentation fault"

#define MAX_NODE 200001
#define MAX_DP 19

using namespace std;

int main()
{
    int next[MAX_NODE][MAX_DP];
    return 0;
}

But, this case do not occur

#define MAX_NODE 200001
#define MAX_DP 19

using namespace std;

int main()
{
    int **next = (int **)malloc(MAX_NODE * sizeof(int *));
    for (int i = 0; i < MAX_NODE; i++)
    {
        next[i] = (int *)malloc(MAX_DP * sizeof(int));
    }
    return 0;
}

what is one make this situation?

g++ version: Apple clang version 12.0.0 (clang-1200.0.32.29) Target: x86_64-apple-darwin20.3.0 Thread model: posix


Solution

  • You are overflowing your stack. Stack space is limited, which is why large objects should be allocated on the heap (new).

    int next[MAX_NODE][MAX_DP]; creates over 10 MB of stack allocations, which is certainly larger than the average stack size.