-   Programming (
-   -   Seemingly random combination of statements causes segmentation fault (C++) (

ErrorBound 07-27-2006 08:57 PM

Seemingly random combination of statements causes segmentation fault (C++)
Hi, I'm trying to figure out what's going wrong in a simulation I'm writing. It probably has something to do with the lot of big arrays. I can get it down to the following:

#include <iostream>
#include <ctime>
#include <cstdlib>

#define BIG 1000000

using namespace std;

int main()
  unsigned int myints[BIG];
  unsigned int myints2[BIG];
  unsigned int myints3[BIG];


  rand() % 5; // can be any number here

  return 0;

As is, this causes a segmentation fault. However if any of the lines are removed or commented out, there are no errors. Also if you take one 0 off of BIG, there are no errors. I don't think I'm out of memory because I can add myints4[BIG], myints5[BIG], etc if the random numbers are removed.

I have no idea what's going on here..:confused:

spooon 07-27-2006 09:40 PM

You are using too much memory on the stack. Maybe getting a random number somehow causes it to try to use memory on the stack, or something, which actually causes the segmentation fault; whereas maybe otherwise it doesn't try to use memory on the stack.

ErrorBound 07-27-2006 09:46 PM

So maybe I should just try sticking some of those arrays on the heap (free store)? And hope it goes away? (stack, heap, I can't keep these names straight)

graemef 07-28-2006 05:47 AM

The loader ld.exe reserves 2Mb of stack, so with two arrays you come in just under the threshold, but with the third array you exceed the limit. This can be changed by using the --stack option of the loader. see man ld. However if you are linking through g++ then you will probably need to use the following switch


for 8Mb of stack memory.

All times are GMT -5. The time now is 11:27 AM.