Expert C Programming

(Jeff_L) #1

The Stack Segment Under UNIX


On UNIX, the stack grows automatically as a process needs more space. The programmer can just
assume that the stack is indefinitely large. This is one of the many advantages that UNIX has over
operating environments such as MS-DOS. UNIX implementations generally use some form of virtual
memory. When you try to access beyond the space currently allocated for the stack, it generates a
hardware interrupt known as a page fault. A page fault is processed in one of several ways, depending
on whether the reference was valid or invalid.


The kernel normally handles a reference to an invalid address by sending the appropriate signal
(segmentation fault probably) to the offending process. There's a small "red zone" region just below
the top of the stack. A reference to there doesn't pass on a fault; instead, the operating system
increases the stack segment size by a good chunk. Details vary among UNIX implementations, but in
effect, additional virtual memory is mapped into the address space following the end of the current
stack. The memory mapping hardware ensures you cannot access memory outside that which the
operating system has allocated to your process.


The Stack Segment Under MS-DOS


In DOS, the stack size has to be specified as part of building the executable, and it cannot be grown at
runtime. If you guess wrongly, and your stack gets bigger than the space you've allocated, you and


your program both lose, and if you've turned checking on, you'll get the STACK OVERFLOW!


message. This can also appear at compiletime, when you've exceeded the limits of a segment.


Turbo C will tell you Segment overflowed maximum size if too much


data or code had to be combined into a single segment. The limit is 64Kbytes, due to the 80x86
architecture.


The method of specifying stack size varies with the compiler you're using. With Microsoft compilers,
the programmer can specify the stack size as a linker parameter. The


STACK:nnnn


parameter tells the Microsoft linker to allow nnnn bytes for the stack.


The Borland compilers use a variable with a special name:


unsigned int _stklen = 0x4000; / 16K stack /


Other compiler vendors have different methods for doing this. Check the programmer reference
guides under "stack size" for the details.


Helpful C Tools


This section contains some lists (grouped by function) of helpful C tools you should know about, and
what they do, in tables 6-1 through 6-4. We've already hinted at a few of these that help you peek
inside a process or an a.out file. Some are specific to Sun OS. This section provides an easy-to-read
summary of what each does, and where to find them. After studying the summary here, read the

Free download pdf