【发布时间】:2013-07-25 07:57:22
【问题描述】:
访问非法指针的程序不会因 SIGSEGV 崩溃。这不是一件好事,但我想知道这是怎么回事,以及这个过程是如何在生产中存活了很多天的。这让我感到困惑。
我已经在 Windows、Linux、OpenVMS 和 Mac OS 中试用过这个程序,他们从未抱怨过。
#include <stdio.h>
#include <string.h>
void printx(void *rec) { // I know this should have been a **
char str[1000];
memcpy(str, rec, 1000);
printf("%*.s\n", 1000, str);
printf("Whoa..!! I have not crashed yet :-P");
}
int main(int argc, char **argv) {
void *x = 0; // you could also say void *x = (void *)10;
printx(&x);
}
【问题讨论】:
-
这是未定义的行为,因此不崩溃是一个非常好的结果。如果你想调试这类事情,请使用适当的内存检查工具。
-
只是我传递了一个指向指针的指针,当 memcpy 尝试取消引用 printx() 函数中的指针并尝试复制一些垃圾 1000 字节时,它应该已经崩溃了
-
内存检查器如 valgrind 尝试报告这类事情。否则没有保修。
-
见:Hotel。
标签: c undefined-behavior