Increasing Stack Size in Linux for GCC C Applications
In Linux, increasing the stack size for a C application compiled with GNU is different compared to macOS. OSX supports the LD_FLAGS option, while Linux does not.
To augment the stack size for a single application in Linux using GCC, you can employ the setrlimit function as follows:
#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; }
Note: Even with this method, avoid declaring large local variables directly in main(). Instead, such variables should be defined in functions called after the stack size has been successfully adjusted. This prevents stack overflows before the size alteration takes effect in main().
The above is the detailed content of How to Increase the Stack Size for GCC C Applications in Linux?. For more information, please follow other related articles on the PHP Chinese website!