0

I am having an odd error when I try to compile my code, which is written in C. The error says

 segmentation fault (core dumped)

In my code, I have a lot of really large double arrays (like of sizes close to 100,000 in length). I initialize one array of doubles and when I try to initialize an array immediately afterwards of the same size (roughly a 100,000 length) it gives me the segmentation fault error. Oddly, it depends on the size of the array. For example if I do

 double arr[70000];       

It gives me the segmentation error but

 double arr[60000];     

does not gives me the error. I am running my code on a linux machine if that helps. I really need many different very large double arrays. What is going on?

Carter
  • 143
  • 6
  • have you tried using gdb? – jcjunction Jun 23 '14 at 22:52
  • 4
    Are these array locals? If so, you're getting a stack overflow... – Chris Dodd Jun 23 '14 at 22:52
  • Duplicate of http://stackoverflow.com/questions/1847789/segmentation-fault-on-large-array-sizes?rq=1 – It'sPete Jun 23 '14 at 22:55
  • 60,000 doubles fit into a half-megabyte of stack; 70,000 doubles don't. I guess your stack size is half a megabyte. Or, more likely, your stack size is larger, but you've enough of these largish arrays that you have blown the limits. Use dynamic memory allocation (`malloc()` et al) to allocate the arrays on the heap. Make sure you free every allocation; you will run out of heap if you don't. (And check that every allocation is successful before using the pointer returned!) – Jonathan Leffler Jun 23 '14 at 22:55
  • The proposed duplicate question is nominally for C++, and is dealing with larger array sizes (4 MiB instead of 0.5 MiB), but is otherwise very likely to be the same problem. – Jonathan Leffler Jun 23 '14 at 22:58

1 Answers1

3

You've encountered a "Stack Overflow"; basically, you've exhausted the stack space available to your program.

If you allocate the arrays on the heap (in heap storage), you probably will be okay.

With C, you'd likely use the malloc instruction to allocate the memory.

And of course, you'll remember to use the free instruction to return the memory when you're done with it.

spencer7593
  • 106,611
  • 15
  • 112
  • 140