Adjusting Stack Size in Linux for C Applications Using GNU Compiler
In Linux, the stack size for a C application compiled with the GNU compiler can be modified to prevent stack overflow errors. While the syntax used in OSX (LD_FLAGS= -Wl,-stack_size,0x100000000) may not work on SUSE Linux, there are alternative methods to achieve the same result.
One approach is to increase the stack size programmatically within the application itself. This can be done using the setrlimit function provided by the
#include <sys/resource.h> int main(int argc, char **argv) { const rlim_t kStackSize = 16 * 1024 * 1024; // min stack size = 16 MB struct rlimit rl; int result; result = getrlimit(RLIMIT_STACK, &rl); if (result == 0) { if (rl.rlim_cur < kStackSize) { rl.rlim_cur = kStackSize; result = setrlimit(RLIMIT_STACK, &rl); if (result != 0) { fprintf(stderr, "setrlimit returned result = %d\n", result); } } } // ... return 0; }
By increasing the stack size within the application, you can ensure that it has sufficient memory allocation to handle complex operations or large data structures without encountering stack overflow errors. It's important to note, however, that excessively large local variables should be declared in functions called from main to prevent stack overflows before the getrlimit/setrlimit code takes effect.
The above is the detailed content of How to Adjust the Stack Size for C Applications on Linux Using GNU Compiler?. For more information, please follow other related articles on the PHP Chinese website!