0

I'm getting the error "Segmentation fault (core dumped)

Either of these approaches work if loops = 207500 or smaller. However if I increase this (e.g. 2100000) I get the error

#include <stdlib.h>

void main()
{
  long i;
  long loops;

  loops = 2075000; // works
  loops = 2100000; // Segmentation fault (core dumped)

  if (1) {       
    int arr[loops]; // stack array
    for (i = 0; i < loops; i++) {
      arr[i] = 3;
    }
  }

  if (1) {
    int *arr = (int *) malloc(sizeof(int) * loops); // heap array
    for (i = 0; i < loops; i++) {
      arr[i] = 3;
    }
  }

}

I'm using Ubuntu 12.04 LTS via Virtual box with 8gb ram allocated

Super Nerd
  • 11
  • 2
  • What you're doing is a classic recipe for producing stack overflow! – devnull Mar 20 '14 at 03:18
  • In OS, there is a ulimit for stack size. In linux, the defaulit is 8192K. You program will use stack: 2100000*4 bytes / 1024 bytes= 8203K is larger than default size. How to get in linux: ulimit -s: stack size (kbytes) 8192 – QJGui Mar 20 '14 at 06:01
  • May I suggest a few improvements in the code? The lines `if (1)` have absolutely no meaning. Also, some C compilers won't let you initialize an array using a varible: `int arr[loops];` won't always compile. – alextikh Mar 20 '14 at 19:48

1 Answers1

1

You are overflowing your stack, the stack space is very limited compared to the heap. You can find typical stack sizes listed Stack Overflow Problems article:

platform    default size       
=====================================
SunOS/Solaris  8172K bytes
Linux          8172K bytes
Windows        1024K bytes
cygwin         2048K bytes 

The alternative would be to dynamically allocate your array via malloc which would use the much more plentiful heap.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740