-2

I'm not too experienced in C, but I've been recently writing some program in the language to speed it up a little bit (it was originally written in python). I don't really have a problem anymore since I already managed to solve my original problem. However, I would like to know why this solution works.

I have a data structure representing complex numbers defined as

typedef struct _fcomplex { float re, im; } fcomplex;

Then I want to create an array of complex numbers as:

fcomplex M[N];

Here N is a large number (something like ~10^6). Then I initialize the array with zeros in a function that essentially runs through all the indices and sets the values in the array. It's something like:

fcomplex num = {0.0, 0.0};
int i;
for (i=0 ; i < N ; i++) {
   M[i] = num;
}

However, when I run the code, it results in a segmentation fault. However, if I use malloc() to allocate space for the array instead as

fcomplex* M = malloc(N*sizeof(fcomplex));

and then do everything as before, the code works fine. Also, for smaller values of N, the code runs fine either way.

As I said, using malloc() already solved the problem, but I would like to know why?

Echows
  • 317
  • 2
  • 5
  • 14
  • Because the stack is limited in memory (assuming you have the large array declared in a function) and declaring a large array results in a stackoverflow. When you dynamically alllocate memory using `malloc`, the array is allocated on the heap which is much bigger than the stack. – Spikatrix Jun 16 '15 at 10:00
  • For large arrays you are better off using operating system memory allocation functions. – user3344003 Jun 16 '15 at 15:52

1 Answers1

4

It depends where you allocated the array. If it's inside a function, then the variable is allocated on the stack, and by default, (I assume you're running linux) the stack size is 8Mb.

You can find it out using ulimit -s and also modify this value, for instance ulimit -s 1000000.

You may want to have a look on those questions:

Community
  • 1
  • 1
Aif
  • 11,015
  • 1
  • 30
  • 44
  • On my Linux machines, the stack limit is generally 8 million bytes, not 8 kilobytes. – Basile Starynkevitch Jun 16 '15 at 10:05
  • You're right, I mean 8192 but the manpage says that the unit is actually 1024-bytes. I've corrected to be more accurate. – Aif Jun 16 '15 at 10:08
  • I allocate the array in the main() function and then pass a pointer to the array as an argument to the function. Thanks, though. – Echows Jun 16 '15 at 11:27