sizeof(array) in C: segmentation fault [duplicate]

£可爱£侵袭症+ 提交于 2020-02-28 07:27:24

问题


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


回答1:


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);
    



回答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;
}


来源:https://stackoverflow.com/questions/28927475/sizeofarray-in-c-segmentation-fault

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!