views:

60

answers:

3

I know this is an OS function. But is there a way of increasing your overall stack or heap size through C? sbrk() is used to change the size of data segment right? Does this imply both stack and heap?

+3  A: 

You mentioned sbrk(), so I'm going to assume you mean Unix/Linux. sbrk() will change the size of the data segment, but usually the stack is in a different memory space than the data segment, to keep people from overwriting the stack and doing evil things. Typically you'll set your stack size before you start the program running by using ulimit from your shell.

Note: sbrk() is deprecated in favor of malloc().

The Open Unix specification defines (and Linux implements) the getrlimit() and setrlimit() functions, which also allow you to play with system limits.

Craig Trader
`getrlimit()` and `setrlimit()` are what `ulimit` actually uses to tweak limits.
caf
A: 

Not through C but in case you didn't see this: http://teaching.idallen.com/c_programming/changingRunTimeStack.html

Greg McNulty
+1  A: 

Virtual memory OSes (when using a CPU with MMU) automatically grow the data/stack segment when needed, up to a maximum. On POSIX systems the maximums can be configured using setrlimit(), as W. Craig Trader said. POSIX defines RLIMIT_DATA, RLIMIT_STACK and RLIMIT_AS for the limits.

malloc() internally uses brk() to grow/shrink the data segment, or mmap()/munmap(), to request/release memory mappings. The stack is grown when the CPU tries to access memory below the allocated stack.

On systems with no MMU (e.g. uClinux), the executable file format usually has a field for the stack size (take a look at the BFLT file format, for instance).

ninjalj