请帮助我理解这个用 C 编写的示例程序。
#include <stdio.h>
int i;
int *tmp;
void anotherFunction(void);
void destroyStack(int);
void main(void)
{
anotherFunction();
fprintf(stderr,
"We will never reach this far\n");
}
void anotherFunction(void)
{
destroyStack(4);
fprintf(stderr,"In another function\n");
}
void destroyStack(int param)
{
tmp = ¶m;
for(i = -200; i < 10; i++)
/* overwrite part of stack*/
printf("%d\n",param), tmp[i] = 0;
}
AFAIK tmp
是一个指向 int 的指针,它被视为一个数组,为什么会这样?作者试图用这个名为“销毁堆栈”的例子来说明什么?什么时候像数组一样使用指针是个好主意?这样编程是否完全合法?
最佳答案
tmp = ¶m;
tmp[i] = 0;
导致写入不属于自己的内存位置。这会导致未定义的行为。这可能会像作者所说的那样破坏堆栈或工作得很好。它只是不是一个有效的 C 程序。
What is the author trying to illustrate with this example called "destroying the stack" ?
显然,S/He 正在尝试演示破坏堆栈。其意图似乎是超出内存范围进行写入,以便它可能破坏堆栈。但是,这是 UB,它可能会或可能不会导致这种情况。
关于c - 理解这个示例程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16752078/