When I want for define to set 1000000, program in process crashed [duplicate]

自闭症网瘾萝莉.ら 提交于 2019-12-25 06:48:23

问题


When I want to #define for SIZE 1.000.000 , my program crashed before it start main function, but when i #define for SIZE 100.000 it work. I have two arrays initialization in my program.

#define SIZE 1000000
char *baza_vocka[SIZE];    
    char b_vocka[SIZE];

EDIT: They are local variables.


回答1:


In case of 1M you're trying to allocate an array on the stack, which is bigger than the stack size. For such sizes you need to allocate the memory on heap.

For example:

int main()
{
    // allocation on the heap
    char **baza_vocka = malloc(sizeof(char*)*SIZE);
    char *b_vocka = malloc(sizeof(char)*SIZE);

    // working code
    baza_vocka[1] = 0x0;
    b_vocka[1] = 'a';

    // cleaning the heap
    free(b_vocka);
    free(baza_vocka);
}



回答2:


I guess that baza_vocka is a local variable, perhaps inside main

You are experimenting some stack overflow, .... Local call frames should usually be small (a few kilobytes) in your call stack

You should not have so big local variables. Allocate such big arrays in the heap using malloc or calloc. Don't forget to test that they are not failing. Read documentation of malloc(3), and don't forget to free such a heap allocated array. Beware of memory leaks & buffer overflows. Use valgrind if available.

On current desktops, stack space is a few megabytes, so you usually should limit each call frame to a few kilobytes (or a few dozens of kilobytes).



来源:https://stackoverflow.com/questions/26721826/when-i-want-for-define-to-set-1000000-program-in-process-crashed

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