-1

I am coming up against a segmentation fault in my code that I can only explain through insufficient available memory. What is happening is that I am trying to create a NxN matrix where N is a large number. For N=8, the programme runs fine, but for N>=16³=5000, I get a segmentation fault automatically. This is ew Is there any simple way of solving this problem? I actually want to simulate sizes of the range N=64³ if possible, so this is a very essential question for me.

My code structure is as follows.

const int N=16**3;
int main(int argc, const char * argv[]) {
double rnorm[N][N];
...
}

void Diluisci(..., double rnorm[N][N]{
...
AdjMatOnestep(rnorm);
}

void AdjMatOnestep(double rnorm[][N]){
...}

So main() calls Diluisci() which calls AdjMatOnestep(), and as soon as I call this last function, I get a segmentation fault. I don't even enter into the first line of it. DDD says "error reading variable: Cannot access memory at address ...".

Any ideas?

ap21
  • 2,372
  • 3
  • 16
  • 32

1 Answers1

2

You're trying to allocate rnorm on the stack, but at 8 bytes for each of the 4096 * 4096 elements, that comes to about 128 MB. There probably isn't enough room on the stack for that amount of storage.

You should use malloc() to create this array on the heap instead.

r3mainer
  • 23,981
  • 3
  • 51
  • 88
  • Would you please mind explaining the difference between the heap and the stack? – ap21 Apr 10 '17 at 21:14
  • 3
    Stackoverflow is for providing solutions to problems, it is not for educating you on elementary issues that you can very easily look up by yourself. – Mike Nakis Apr 10 '17 at 21:16