Big array gives segmentation error in C

前端 未结 4 2067
情话喂你
情话喂你 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 ).

    Example:

    unsigned long long numbs = malloc(arr_size * sizeof *numbs);
    /* And later, when you're done with it */
    free(numbs);
    

提交回复
热议问题