Given the fact that local variables inside a function in C get pushed to the stack once the function is called (After pushing the variables being passed to the function), is there any limit to the quantity of said variables before the stack buffer overflows? Or that limit is just given by the amount of RAM a determined host has?
I've tried to test this by creating a 4,6gb .C file with a single function having 25000*13 variables declared and initialized to 0. Said function is called inside main() but it compiled just fine (With -O0) and it didn't crash.
EDIT: The number was wrong! My bad.
CodePudding user response:
For example according to the C Standard (5.2.4.1 Translation limits)
1 The implementation shall be able to translate and execute at least one program that contains at least one instance of every one of the following limits:
— 4095 external identifiers in one translation unit
— 511 identifiers with block scope declared in one block
CodePudding user response:
The default stack size for the main thread is 8 MiB on macOS (from the ld
man page), 2 MiB on Linux (per the --stack
switch here), and 1 MiB on Windows (per this page). Additional threads created within the program may have smaller stacks. (Note: The various sources cited use “MB” or “Mb”; I have interpreted these in context to mean 1,048,576 bytes = 1 MiB.)
A different stack size can be requested when linking the program into an executable file.
Functions use stack space for various things, including passing arguments, establishing stack frames for throwing exceptions, sometimes debugging information, and temporary work space, so there is not a direct correlation between the amount of memory used for the stack and the number of variables that can be defined.