78

Today I was helping a friend of mine with some C code, and I've found some strange behavior that I couldn't explain him why it was happening. We had TSV file with a list of integers, with an int each line. The first line was the number of lines the list had.

We also had a c file with a very simple "readfile". The first line was read to n, the number of lines, then there was an initialization of:

int list[n]

and finally a for loop of n with a fscanf.

For small n's (till ~100.000), everything was fine. However, we've found that when n was big (10^6), a segfault would occur.

Finally, we changed the list initialization to

int *list = malloc(n*sizeof(int))

and everything when well, even with very large n.

Can someone explain why this occurred? what was causing the segfault with int list[n], that was stopped when we start using list = malloc(n*sizeof(int))?

1
  • Exactly what i was searching for, i was having the same problem in harckerank array manupulation problem.
    – Kapil
    Oct 9, 2020 at 1:46

9 Answers 9

177

There are several different pieces at play here.

The first is the difference between declaring an array as

int array[n];

and

int* array = malloc(n * sizeof(int));

In the first version, you are declaring an object with automatic storage duration. This means that the array lives only as long as the function that calls it exists. In the second version, you are getting memory with dynamic storage duration, which means that it will exist until it is explicitly deallocated with free.

The reason that the second version works here is an implementation detail of how C is usually compiled. Typically, C memory is split into several regions, including the stack (for function calls and local variables) and the heap (for malloced objects). The stack typically has a much smaller size than the heap; usually it's something like 8MB. As a result, if you try to allocate a huge array with

int array[n];

Then you might exceed the stack's storage space, causing the segfault. On the other hand, the heap usually has a huge size (say, as much space as is free on the system), and so mallocing a large object won't cause an out-of-memory error.

In general, be careful with variable-length arrays in C. They can easily exceed stack size. Prefer malloc unless you know the size is small or that you really only do want the array for a short period of time.

7
  • 2
    Great answer! I was wondering if there is also a difference in speed?
    – Tropilio
    Dec 25, 2017 at 1:07
  • 1
    Due to the effects of locality of reference I’d suspect the stack-allocated array is faster to access, and malloc itself is much slower than just bumping a stack pointer. But really, it’s best to use whatever approach is more appropriate for the task at hand. Dec 25, 2017 at 3:03
  • Or, if you declare int arr[1000000]; outside of any functions they are automatically set to zero and will be stored on the heap. Feb 7, 2020 at 22:19
  • @DSOI__UNUNOCTIUM Those arrays would have static storage duration. Are you sure they'd be stored on the heap? Feb 7, 2020 at 22:25
  • I have allocated arrays of sizes up to a couple hundred thousand before. I'll test it out right now. Feb 9, 2020 at 4:18
16
int list[n]

Allocates space for n integers on the stack, which is usually pretty small. Using memory on the stack is much faster than the alternative, but it is quite small and it is easy to overflow the stack (i.e. allocate too much memory) if you do things like allocate huge arrays or do recursion too deeply. You do not have to manually deallocate memory allocated this way, it is done by the compiler when the array goes out of scope.

malloc on the other hand allocates space in the heap, which is usually very large compared to the stack. You will have to allocate a much larger amount of memory on the heap to exhaust it, but it is a lot slower to allocate memory on the heap than it is on the stack, and you must deallocate it manually via free when you are done using it.

1
  • 1
    "Using memory on the stack is much faster than the alternative", here do you mean by "allocation" or "accessing"? AFAIK, stack allocation is much faster but does it also hold true for accessing (read/write)? Thanks Aug 5, 2015 at 18:58
3

int list[n] stores the data in the stack, while malloc stores it in the heap.

The stack is limited, and there is not much space, while the heap is much much bigger.

1

int list[n] is a VLA, which allocates on the stack instead of on the heap. You don't have to free it (it frees automatically at the end of the function call) and it allocates quickly but the storage space is very limited, as you have discovered. You must allocate larger values on the heap.

1

This declaration allocates memory on the stack

    int list[n]

malloc allocates on the heap.

Stack size is usually smaller than heap, so if you allocate too much memory on the stack you get a stackoverflow.

See also this answer for further information

1

Assuming you have a typical implementation in your implementation it's most likely that:

int list[n]

allocated list on your stack, where as:

int *list = malloc(n*sizeof(int))

allocated memory on your heap.

In the case of a stack there is typically a limit to how large these can grow (if they can grow at all). In the case of a heap there is still a limit, but that tends to be much largely and (broadly) constrained by your RAM+swap+address space which is typically at least an order of magnitude larger, if not more.

1

If you are on linux, you can set ulimit -s to a larger value and this might work for stack allocation also. When you allocate memory on stack, that memory remains till the end of your function's execution. If you allocate memory on heap(using malloc), you can free the memory any time you want(even before the end of your function's execution).

Generally, heap should be used for large memory allocations.

0

When you allocate using a malloc, memory is allocated from heap and not from stack, which is much more limited in size.

0
   int array[n];

It is an example of statically allocated array and at the compile time the size of the array will be known. And the array will be allocated on the stack.

   int *array(malloc(sizeof(int)*n);

It is an example of dynamically allocated array and the size of the array will be known to user at the run time. And the array will be allocated on the heap.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.