3

Hi i get a weird segmentation fault from this code:

int main(void){

  int array1[10000000];

  int n = sizeof(array1);

  printf("%d \n", n );

    return 0;
}

However if i change

int array1[10000000];

to

int array1[1000000];  ( one less zero)

The program works and prints 4000000

I'm running it on Fedora 21(64bits)

Is this because there is a maximum size for array in C? Thank you in advance

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
齐天大圣
  • 1,169
  • 5
  • 15
  • 36

2 Answers2

16
int array1[10000000];

is too large for your stack and you overflow your stack whereas

int array1[1000000];

is large, but does not overflow your stack as the array fits in it.

Note that the size of the stack can vary on different systems and can be set to a particular size.

Methods to solve it:

  1. Make the array static.
  2. Make the array global.
  3. Allocate memory on the heap using malloc from stdlib.h:

    int *array1;
    array1 = malloc(10000000 * sizeof(int));
    
    if(array1 == NULL) /* If `malloc` failed to allocate memory */
    {
        fputs("Oops! `malloc` failed to allocate memory!\n", stderr);
        exit(-1); /* Exit the program with a return value of `-1` ; Requires `stdlib.h` */
    }
    
    /* Use the array and after use, free it using */
    
    free(array1);
    
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
2

An additional method to solve it is to increase stack size with setrlimit. Standard size is 8 MB, at least on my Linux.

#include <stdio.h>
#include <errno.h>
#include <sys/resource.h>

static int setstacksize(rlim_t stacksize)
{
    struct rlimit rl;
    int res;

    if ((res = getrlimit(RLIMIT_STACK, &rl)) != 0) {
        fprintf(stderr, "getrlimit result = %d, errno = %d\n", res, errno);
        return res;
    }
    if (rl.rlim_cur >= stacksize) return res;
    rl.rlim_cur = stacksize;
    if ((res = setrlimit(RLIMIT_STACK, &rl)) != 0) {
        fprintf(stderr, "setrlimit result = %d, errno = %d\n", res, errno);
    }
    return res;
}

static int func(void){

    int array1[10000000];
    int n = sizeof array1;

    printf("%d\n", n);
    return 0;
}

int main(void){
    setstacksize(48 * 1024 * 1024);
    func();
    return 0;
}
4566976
  • 2,419
  • 1
  • 10
  • 14