C51: CHECKING FOR STACK UNDERFLOW AT RUNTIME

本文介绍如何在C51程序中检查栈指针是否发生下溢。通过修改启动代码添加栈底标签,并定义宏来比较栈指针与栈底地址,确保程序运行时栈的安全。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C51: CHECKING FOR STACK UNDERFLOW AT RUNTIME


Information in this article applies to:


C51 All Versions


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 = 0×81; /* 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


SEE ALSO
C51: STACK AND REENTRANT STACK SYMBOLIC NAMES
C51: CALCULATING STACK SIZE
C51: STACK POINTER INITIALIZATION IN STARTUP CODE
C51: LOCATING THE STACK AFTER IDATA VARIABLES
C51: STACK UTILIZATION
DSCOPE: DETECTING STACK OVERFLOW
通过C51: CHECKING FOR STACK UNDERFLOW AT RUNTIME.


 Posted by Ian at 04:11  Tagged with: C51, Stack
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值