0

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
lotoflaugh
  • 63
  • 8
  • 1
    I am curious. Do you define `char *baza_vocka[SIZE];` inside a function (`main` or any other function) or are they declared outside a function at global scope? – Michael Petch Nov 03 '14 at 19:44
  • That observation is a bit soft. I can't imagine this would cause a problem in global scope. – Karoly Horvath Nov 03 '14 at 19:45
  • 2
    What does "crash" mean? – Falmarri Nov 03 '14 at 19:45
  • 1
    You are experimenting some *stack overflow*, .... – Basile Starynkevitch Nov 03 '14 at 19:45
  • With the edit that these are local variables you are encountering a stack overflow because the arrays are too big to fit on the stack. I wrote an answer to another *related* post with some extra information here: http://stackoverflow.com/questions/26077874/segmentation-fault-in-scanf – Michael Petch Nov 03 '14 at 20:01

2 Answers2

3

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);
}
Anton K
  • 4,658
  • 2
  • 47
  • 60
1

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

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547