健仔说到的一个问题。
void Test(void) {
char str[2];
strcpy(str, "hello world");
printf(str);
cout << "fuck" << endl;
}
这样的代码,其实在strcpy时已经出错了,为什么还可以继续输出?然后才报错?
查看strcpy的源代码如此:
char * strcpy(char * dest,const char *src)
{
char *tmp = dest;
while ((*dest++ = *src++) != '\0')
/* nothing */;
return tmp;
}
的确没有差错的地方。
但是不是应该在输出前就报错嘛?
程序的空间分配应该是这样的:
+------------------+ 内存低端
| 程序段 |
|------------------|
| 数据段 |
|------------------|
| 堆栈 |
+------------------+ 内存高端
数据段分配的地址越界影响到了堆栈。多出来的字符“llo world\0”覆盖了main函数的出口,导致函数退出时,解栈错误。
程序报错信息是:
Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention.
ESP指的是extended stack pointer。就是函数调用后esp指针不能正确保存,也就覆盖掉了出口。
所以是可以继续执行程序段的,但是出口就错了。应该是酱紫.....