ARM Technical Support Knowledge Articles

CHECKING FOR STACK UNDERFLOW AT RUNTIME

Applies to: C51 C Compiler

Answer


Information in this article applies to:


QUESTION

I want to test the stack pointer (SP) in the main loop of my program to be sure that it has not underflowed. To do this, I need to get the address that SP is initialized to by the startup code. How can I do this?

ANSWER

First, you must modify the startup code to include a label for the bottom of the stack. Modify the startup code (STARTUP.A51) as shown below:

?C_C51STARTUP   SEGMENT   CODE
?STACK          SEGMENT   IDATA

                RSEG    ?STACK
                PUBLIC  stackbot         ; Add this public declaration
stackbot:       DS      1                ; Add the stackbot label

                EXTRN CODE (?C_START)
                PUBLIC  ?C_STARTUP

                CSEG    AT      0

Note that the startup code loads the stack pointer as follows:

                MOV     SP,#?STACK-1

This means that in the main function, SP must be compared to the address of stackbot minus 1!

In the file that contains the main C function, you must add the following definitions and declarations:

extern unsigned char const idata stackbot [];   /* Bottom of the stack */
sfr SP = 0x81;                                  /* Stack pointer */
#define STACK_START ((unsigned char) (&stackbot [-1]))

Note that stackbot is the bottom of the stack as declared in the STARTUP.A51 file. This is defined in the ?STACK segment in IDATA. The extern declaration is an array because you must access the address of stackbot - 1. Using an array, we can negatively index (using -1) and obtain this address as a constant.

The following simple program shows how to use the STACK_START macro and the SP SFR to test the stack pointer.

/*---------------------------------------------------------
---------------------------------------------------------*/
void stack_error (void)
{
/*** Handle stack errors here ***/
}

/*---------------------------------------------------------
---------------------------------------------------------*/
void main (void)
{
while (1)
  {
  /*** Do Stuff ***/


  if (SP != STACK_START)
    {
    stack_error ();
        }
  }
}

/*---------------------------------------------------------
---------------------------------------------------------*/

SEE ALSO

Article last edited on: 2001-11-16 00:00:00

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential