-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?

3
  • 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? Commented Aug 8, 2016 at 1:26
  • 1
    You probably ran out of stack space... This seems relevant: stackoverflow.com/questions/2780100/… Commented Aug 8, 2016 at 1: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 Commented Aug 8, 2016 at 14:50

1 Answer 1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.