Home > Backend Development > C++ > How Can I Change the Stack Size of a C Application in Linux Using GCC?

How Can I Change the Stack Size of a C Application in Linux Using GCC?

Barbara Streisand
Release: 2024-12-22 19:22:13
Original
330 people have browsed it

How Can I Change the Stack Size of a C   Application in Linux Using GCC?

Changing Stack Size for C Applications in Linux with GCC

In Linux, unlike macOS, the LD_FLAGS=-Wl,-stack_size option is not recognized by the GNU compiler. To adjust stack size for a single C application, the setrlimit function can be utilized programmatically.

#include <sys/resource.h>

int main() {
  const rlim_t kStackSize = 16 * 1024 * 1024;  // 16 MB

  struct rlimit rl;
  int result;

  // Get current stack size limits
  result = getrlimit(RLIMIT_STACK, &rl);
  if (result == 0) {
    // If current stack size is less than desired, adjust it
    if (rl.rlim_cur < kStackSize) {
      rl.rlim_cur = kStackSize;
      result = setrlimit(RLIMIT_STACK, &rl);
      if (result != 0) {
        // Error handling
      }
    }
  }

  // Your code...

  return 0;
}
Copy after login

When implementing this solution, it's crucial to place large local variable declarations within functions that are called from main() rather than directly in main(). Otherwise, a stack overflow may occur before the stack size can be augmented.

The above is the detailed content of How Can I Change the Stack Size of a C Application in Linux Using GCC?. 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