weird Segmentation fault

I have this piece of code which works fine

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <cstdio>
#include <iostream>
#include <cmath>

#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_rng.h>

#define N 1500000

int main (void)
{
  gsl_rng * r;
  const gsl_rng_type  * T;

  gsl_rng_env_setup();

  T = gsl_rng_default;
  r = gsl_rng_alloc(T);

  double z[N];

  for (int i = 0; i<N; i++)
  	z[i] = gsl_ran_gaussian(r, 1);

  return 0;
}


However I get the following error message

<terminated>gdb/mi (6/17/10 4:52 PM) (Exited. Signal 'SIGSEGV' received. Description: Segmentation fault.) gsl_rng_env_setup.

If i change N to be defined as, say, 1600000,
this is while I have enough memory for arrays even way larger than this size.

and I do not understand what the hell N has to do with gsl_rng_env_setup

can anyone help me with this?
Try it using std::deque<double> z(N). You only have so much stack memory. Sometimes larger arrays have to be allocated using heap memory.

EDIT: Sorry for my typo.
Last edited on
where exactly should I use this command?
which line does it replace?
can you explain more
std::deque<double>(N) z; is the line that should replace 21.
EDIT: Typo. It should have been std::deque<double> z(N);

More on deques:
http://cplusplus.com/reference/stl/deque/

-Albatross
Last edited on
I get

syntax error: expected ';' before z

if i do this replacement;
(i also added #include <deque>)
Last edited on
Whoops. Typo.
std::deque<double> z(N);

:D

-Albatross
thanks that worked,
but this seems to be a C++ solution,
do you know of a solution which also works in C?
Maybe an array of pointers would work for you when you're writing stuff in C. Just remember to use malloc().

-Albatross
Last edited on
If you need a C solution then why are you including C++ headers? Anyway if you do it with C you need to learn how to dynamically allocate arrays with malloc. Sorry I can't help you with that. I'm sure that you can figure it out if you do a web search on malloc and array.
The C way:

1
2
3
4
5
double* z = malloc(sizeof(double) * N);

// do stuff with 'z' here

free(z);
But then I can use

1
2
3
double * z  = new double [N];
// ....
delete [] z;


in C++ as well;
what is the advantage of using
 
std::deque<double>  z(N);


other than that I do not have to take care of memory redemption.

speed of the code is of my higher priority,
especially because I want to push N as large as the available memory allows
and I wonder that using deque has any speed disadvantage
Last edited on
Topic archived. No new replies allowed.