strcpy源码解说

今天上了一节课,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.访问到非法空间。// 因访问到非法的内存空间导致的程序非正常结束。也就是说,程序可以编译成功,只不过在后续的调用strcpy函数,因访问到了非法的内存空间而导致程序非正常结束。所以说,老师说的不能说完全正确,也不能说完全错误。

2.短字符复制长字符的一部分字符。//这是非常危险的,要慎重使用。(ps: 2015/2/2更新)


这就是结论。


// 2015/2/2 然后又遇到了一个很蛋疼的问题。

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;

const int N = 104;

int main()
{
    char str[N];
    memset(str, '0', sizeof(str));
    str[N] = '\0';
    printf("%s\n", str);
    puts("yeah you are right.!");
    char str1[N];
    strcpy(str1, str);
    str1[N] = '\0';
    printf("%s\n", str1);
    return 0;
}

// 这个程序竟然不知道为什么运行不过。 表示百思不得其解。。。

是系统上的问题,还是函数本身的问题。自己以前也没有遇到过这种问题啊。。。很是不解。尴尬。。!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值