c - 理解这个示例程序

标签 c arrays pointers stack

请帮助我理解这个用 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 = &param;
 for(i = -200; i < 10; i++)
 /* overwrite part of stack*/
 printf("%d\n",param), tmp[i] = 0;
}

AFAIK tmp 是一个指向 int 的指针,它被视为一个数组,为什么会这样?作者试图用这个名为“销毁堆栈”的例子来说明什么?什么时候像数组一样使用指针是个好主意?这样编程是否完全合法?

最佳答案

tmp = &param;
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/

相关文章:

c - 如何将一个进程的标准输出重定向到另一个进程的标准输入?

c - 警告:函数的隐式声明

php - 如何将 session 中保存的数据注册到数据库中?

c++ - 递归函数,将链表的末尾附加到另一个链表的开头,并返回指向新列表开头的指针

comp.lang.c 常见问题解答 : Function that can return a pointer to a function of the same type

c - 如何提高cmuSphinx的准确率?

c++ - OpenProcessToken 从本地系统服务失败并出现 ERROR_ACCESS_DENIED

arrays - 在 Firebase SWIFT 中查询数组

Java 将两个 BigInt 对象相乘

c - 如何解决: "cast to pointer from integer of different size" warning in C code?