Search code examples
cstack-overflowturbo-c

Why does stack overflow occur if we do not declare our buffer as a global variable in C?


Just read somewhere that,

when large buffers are used they must be made global variables otherwise stack overflow occurs.

But i am unable to get why it would happen?

(This is for C language compilers Turbo C on windows).


Solution

  • Typically, the executable file header, and OS loader, place a lower limit on the maximum stack size than they do on the global/static data.

    Your linker is responsible for assembling the executable header and may be instructed to set a greater, (or smaller), maximum stack size for the executable image, so you could instruct the linker to raise that limit to accommodate your big buffer.

    If you need a large buffer and don't want to increase the maximum stack, you could dynamically-allocate the buffer space at runtime.

    The last option you should consider is using statics/globals. Such code/data is not reeentrant and so not thread-safe:(