-3

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?

2
  • 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. Commented Jun 16, 2015 at 10:00
  • For large arrays you are better off using operating system memory allocation functions. Commented Jun 16, 2015 at 15:52

1 Answer 1

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:

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

3 Comments

On my Linux machines, the stack limit is generally 8 million bytes, not 8 kilobytes.
You're right, I mean 8192 but the manpage says that the unit is actually 1024-bytes. I've corrected to be more accurate.
I allocate the array in the main() function and then pass a pointer to the array as an argument to the function. Thanks, though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.