1

I'm receiving a segmentation fault when performing the following action. Say I define some grid size as follows.

#define DIM 512

int x = DIM;
int y = DIM;  

Now I want to allocate some 2D array with these dimensions

complex double arr[x][y];

This produces a segmentation fault, where as this call

complex double arr[512][512];

runs smoothly. I'm sure it's something obvious that I'm missing here, but if someone has a step in the right direction I'd certainly be most obliged.

4
  • Are you doing it on the stack ? Commented Jan 24, 2012 at 20:57
  • 6
    Can you post a complete, minimal example that compiles and exhibits your problem along with any switches you pass to the compiler? Commented Jan 24, 2012 at 21:00
  • and certainly you should show us where the segfault occurs. It could be that your problem is just somewhere else, only showing here because you change some arbitrary condition that triggers your segfault. Commented Jan 24, 2012 at 21:16
  • Are x=y=512 the actual dimensions with which you get a segfault? Commented Jan 24, 2012 at 22:31

1 Answer 1

2

When you define an array statically:

complex double arr[512][512];

The compiler knows how large it will be, so it reserves memory appropriately. However, When you declare an array variably,

complex double arr[x][y];

which you can only do this within a function, the compiler can't know how big it will be, so it can't reserve an appropriate space for it. The space will be allocated on the stack, and your stack evidently doesn't have the 4MB required for that array.

Ex:

double arr1[10240][10240];

int main() {
        double arr2[10240][10240];
        int i = 10240;
        int j = 10240;
        double arr3[i][j];
}

arr3 causes a segfault when run, comment it out and it will work. arr1 is put in the data section, arr2 is put on the stack, but the stack is made large enough to hold it (which the compiler can do since it is of known size). arr3, however, is not of a fixed size, so the compiler can't reserve space for it. The program tries to allocate it on the stack, but its too big, so the allocation causes a segfault.

Sign up to request clarification or add additional context in comments.

3 Comments

Actually, the example is too simple, at least for recent gcc's. You'd need to use the array to cause a segfault.
@DanielFischer It segfaulted on mine, I believe it's 4.4, I can check when I get back to work.
Could of course also be OS dependent. Ran here without problems with 4.5.1 on 64-bit linux when only allocating and not using. But regardless of whether the example segfaults on this or that setup, the principle is the important thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.