-1

This is my part of the code that occurred and segmentation fault:

int main (int argc, char *argv[]) {
  printf ("====================================================\n");
  double pointArray[MAX_NUM_OF_POINTS][DIMENSION];
  double range;
  int num_of_nearest;
  double queryPoint[DIMENSION];
  int counter;
  int dist;
  int num;
  printf ("====================================================\n");
}

where MAX_NUM_OF_POINTS was defined to be 100,000,000.

However, when I changed this number to be smaller like 100,000, the segmentation fault disappeared.

Could anyone tell me the reason?

nalzok
  • 14,965
  • 21
  • 72
  • 139
Cui Zheng
  • 17
  • 4
  • It's hard to answer without seeing the rest of your program. Can you use breakpoints or print statements to see where exactly the segmentation fault occurs? – codebender Aug 08 '16 at 01:26
  • 1
    You probably ran out of stack space... This seems relevant: http://stackoverflow.com/questions/2780100/is-there-any-limit-on-stack-memory – obe Aug 08 '16 at 01:27
  • `pointArray` is 800'000'000 bytes for *each* dimension which is almost 800MB whereas the default stack size on Windows is only 1MB and on Linux is 4/8MB. If DIMENSION is 3 then your array is aready ~2.4GB – phuclv Aug 08 '16 at 14:50

1 Answers1

2

Local variables are created on the stack, which has a limited amount of space. By attempting to create an array of at least 100000000 doubles, each of which is probably 8 bytes, it is too large for the stack and causes a segfault.

If you declare the array as a global, it will not reside on the stack but in the data segment instead, which can handle larger variables. Alternately, you can create the array dynamically using malloc in which case it lives on the stack.

This however raises the question as to why you need an array that large. You may need to rethink your design to see if there is a more memory efficient way of doing what you want.

dbush
  • 205,898
  • 23
  • 218
  • 273