Big array gives segmentation error in C

前端 未结 4 2014
情话喂你
情话喂你 2020-12-04 02:48

I am really new to C, so I am sorry if this is a absolute beginner question, but I am getting a segmentation error when I am building large array, relevant bits of what I am

相关标签:
4条回答
  • 2020-12-04 03:21

    numbs is a Variable Length Array (VLA).

    VLAs can be created only in block scope (i.e., inside a function). They're allocated like any other local variable, typically on the stack.

    Unfortunately, the language doesn't provide a way of detecting or handling allocation failures for local variables. If you allocate too much memory, your program will crash if you're lucky.

    Large objects whose size isn't known at compile time should be allocated via malloc() (which means you need to keep track of the allocation and release them with free()).

    Incidentally, there's no need to cast arr_size to int. And both ust_limit and arr_size should be of type size_t (defined in <stddef.h>).

    Example:

    unsigned long long numbs = malloc(arr_size * sizeof *numbs);
    /* And later, when you're done with it */
    free(numbs);
    
    0 讨论(0)
  • 2020-12-04 03:43

    You array stores on stack frame, which has a limit to its size, use malloc instead.

    unsigned long long *numbs = malloc(arr_size * sizeof(long long));
    // don't forget to free after use
    free(numbs)
    
    0 讨论(0)
  • 2020-12-04 03:43

    You're consuming too much stack. The limit is platform dependent.

    The exact limit depends on the OS. These limits can be changed to some extent on some operating systems .

    For large amounts of memory, you should be using the head with malloc and/or calloc (and free).

    0 讨论(0)
  • 2020-12-04 03:45

    You are most likely getting a stack overflow, since you are creating a very large array on the stack. To avoid this, allocate the memory dynamically:

    unsigned long long *numbs = malloc(arr_size * sizeof(unsigned long long));
    

    Later, when you are finished with the array, free it again:

    free(numbs);
    
    0 讨论(0)
提交回复
热议问题