famaral42
famaral42

Reputation: 773

Stack 8MiB, then why this code "almost" works?

I read everywhere.
The stack has 8MB, that's why you should use pointer, to store stuff in the heap.

Well, on my machine the code bellow works with 11MB of char, but not with 12MB.
Is my char c[Nc] array storage in the so called heap?

#include <stdio.h>

int main()
{
    int Nc = 1024*1024;  // megabyte

    Nc = Nc * 11;  // works
    //Nc = Nc * 12;  // Segmentation fault (core dumped)

    char c[Nc];

    c[0] = 'A';
    c[Nc-1] = 'Z';

    printf("%dmb\n", Nc/1024/1024);

    printf("%c-%c\n", c[0], c[Nc-1]);

    return 0;
}

Any explanations?
I am just "user" not a programmer.

Upvotes: 1

Views: 140

Answers (1)

cmwt
cmwt

Reputation: 349

It looks like you are compiling your program with at least some optimizations. When I compile your code, on GCC or Clang, with anything other than -O0 the compiler optimizes away the creation of the char array. (Godbolt link)

If you compile your program with -fsanitize=undefined it will catch this as undefined behavior.

Putting such a large array on the stack is generally considered bad practice. Large objects should be statically allocated or allocated on the heap. The operating system sets its default stack allocation to a level where most programs will not need to worry about it, it is not a guarantee. It is your responsibility as a programmer to make sure that your program has enough stack space to run. If you need to get or check the amount of stack space, you can use getrlimit() and setrlimit(). See man getrlimit for more information.

Upvotes: 4

Related Questions