首先看一段必现的Crash程序。
char* do_strcpy(char* pDstStr, const char* pSrcStr)
{
char* pRet = pDstStr;
while ((*(pDstStr++) = *(pSrcStr++))!='\0'){;}
return pRet;
}
bool __strcpy(const char* pSrcStr)
{
char destStr[8] = {0};
do_strcpy(&destStr[-24], pSrcStr);
printf("ok\n");
printf(destStr);
return true;
}
int main()
{
printf("input a string: \n");
char strInput[256] = {0};
fgets(strInput, 256, stdin);
__strcpy(strInput);
getchar();
return 0;
}
这段代码必然crash,下面分析下原因。
输入一段长字符串,比如50个1,执行到__strcpy中后,在栈上申请一个char[],长度为8+1.然后调用do_strcpy并传参,然后执行printf("ok\n").
函数的调用需要压栈,在调用do_strcpy前,在栈上开辟了9个字节的空间,调用do_strcpy时,首先将返回后的下一个指令地址压栈,即将printf("ok\n")的函数地址压栈。然后穿参数,在vc上参数从右到左压栈,最后传入do_strcpy的函数地址。待函数执行完后依次出栈&