Home > Backend Development > C++ > How to Increase the Stack Size for GCC C Applications in Linux?

How to Increase the Stack Size for GCC C Applications in Linux?

Patricia Arquette
Release: 2024-12-26 09:02:10
Original
820 people have browsed it

How to Increase the Stack Size for GCC C   Applications in Linux?

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template