今天上了一节课,Linux操作系统。
课上老师讲到一个问题比较感兴趣,就记了下来。研究一下。
问题:一个长的字符串对一个短的字符空间进行使用strcpy()。会出现什么情况?
Code:
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <cmath> using namespace std; const int MAX = 128; const int MIN = 64; void fun(char *s) { char str2[MIN]; strcpy(str2, s); for(int i = 0; i < strlen(str2); i ++){ printf("%d %c", i, str2[i]); } return ; } int main() { char str1[MAX]; for(int i = 0; i < MAX; i ++){ str1[i] = 'a'; } fun(str1); return 0; }
老师的结论是:程序会出现不能运行。(表示很是怀疑这种结论)
那么,问题就归结到了strcpy()的实现方法上了。就特别找了一下关于这个函数的源码。
这里有个了解,目测是一个面试题目吧。总结挺好。很好的解释了strcpy这个函数。
http://blog.csdn.net/cazicaquw/article/details/7044602
不过这个不是我想要看到的结果。我想要看下,系统函数的实现方法。
看到了一种貌似:
/*** *char *strcpy(dst, src) - copy one string over another * *Purpose: * Copies the string src into the spot specified by * dest; assumes enough room. * *Entry: * char * dst - string over which "src" is to be copied * const char * src - string to be copied over "dst" * *Exit: * The address of "dst" * *Exceptions: *******************************************************************************/ char * __cdecl strcpy(char * dst, const char * src) { char * cp = dst; while( *cp++ = *src++ ); /* Copy src over dst */ return( dst ); }
可以看到,我们的系统函数实现上有很大的漏洞。也就是说鲁棒性很弱。
没有检查一些必要的检查。
所以,我们可以得出结论。
程序的可以运行的。只不过,会出现
1.访问到非法空间。
2.短字符复制长字符的一部分字符。
这就是结论。