In C , the stack size can be adjusted during compilation to meet the specific memory requirements of a particular application. While the LD_FLAGS option works well in macOS with g , Linux distributions such as SUSE Linux use a different approach.
To increase the stack size in Linux for a single application using GCC, two main methods are commonly employed:
The ulimit -s command can be used to set the stack size limit for a specific user or process. However, this method requires elevated privileges and must be executed before launching the application. For example:
ulimit -s unlimited
Alternatively, the stack size can be set programmatically within the application code using setrlimit. This method is more portable and allows applications to adjust their stack size dynamically at runtime. The following code snippet demonstrates how to increase the stack size to 16 MB:
#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 that even with this method, it is important to avoid declaring large local variables in main() as stack overflow can occur before the stack size adjustment takes effect.
The above is the detailed content of How Can I Change the Stack Size for C Applications in Linux?. For more information, please follow other related articles on the PHP Chinese website!