Maxim Mayers
Maxim Mayers

Reputation: 185

A segmentation fault error with 2D array

There is a weird segmentation fault error. The following code runs fine

#include <stdlib.h> 
#include <stdio.h>
main()
    {
    int matrixSize = 1000;
    int i,j;

    double a[matrixSize][matrixSize];
    for (i = 0; i < matrixSize; i++)
        for (j = 0; j < matrixSize; j++)
            a[i][j] = rand() % 10;

        double b[matrixSize][matrixSize];
    for (i = 0; i < matrixSize; i++)
        for (j = 0; j < matrixSize; j++)
            b[i][j] = rand() % 10;
    return 0;
}

But when I try to initialize one more 2D array, I get "segmentation fault" exception:

#include <stdlib.h>
#include <stdio.h>
main()
{
    int matrixSize = 1000;
    int i,j;

    double a[matrixSize][matrixSize];
    for (i = 0; i < matrixSize; i++)
        for (j = 0; j < matrixSize; j++)
            a[i][j] = rand() % 10;

    double b[matrixSize][matrixSize];
    for (i = 0; i < matrixSize; i++)
        for (j = 0; j < matrixSize; j++)
            b[i][j] = rand() % 10;

    return 0;
}

What is the potential cause?

Upvotes: 2

Views: 240

Answers (2)

Jens Gustedt
Jens Gustedt

Reputation: 78903

As tpg2114 says allocating as large matrices is not a good idea. Easiest is to allocate it like that

double (*a)[matrixSize] = malloc(sizeof(double[matrixSize][matrixSize]));
.
free(a);

Then you can continue to use your nested for loops for initialization without problems as before.

NB:

  • since you use a variable for the dimensions your matrix is technically a variable length array, that is only available with C99
  • your definition for main is not conforming to the standard. In your case you should use int main(void) { ... }. since a conforming compiler should capture this, it looks that you don't use the correct options for your compiler or that you ignore warnings that he gives you.
  • since they are representing sizes, your variables matrixSize, i and j should be of type size_t and not int.

Upvotes: 0

tpg2114
tpg2114

Reputation: 15100

You are exceeding the stack size most likely.

In the terminal you are using to run this, try typing

ulimit -s unlimited

and re-run, assuming you are on a Linux system using bash (or sh).

If you have to use arrays that size, you can make them dynamic so they are on the heap rather than the stack if changing the stack size is problematic for some reason.

Upvotes: 10

Related Questions