strcpy的是如何实现的? [英] How is strcpy implemented?

查看:110
本文介绍了strcpy的是如何实现的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于使用strcpy的问题。我知道ANSI C标准说:源和目的一定不能重叠,否则该行为是未predictable。我告诉你一件code如我所料,如果是使用Linux下的旧的GNU C编译器编译的作品的。

I have a question about using strcpy. I know the ANSI C standard says : source and destination must not overlap, otherwise the behaviour is unpredictable. I show you a piece of code that works as I expect if it is compiled using an old gnu C compiler under Linux.

#include <string.h>
#include <stdio.h>

char S[80],*P;

int main() {
    strcpy(S,"abcdefghi\r\njklmnopqr\r\nstuvwxyz\r\n");
    for (P=S; P=strchr(P,'\r'); P++) strcpy(P,P+1);
    printf("%s\n",S);
    return 0;
}

这个序列中删除从输入字符串每 \\ r (回车)。我知道(从Kernigham和Ritchie)对于strcpy的一个非常简单的实现如下

This sequence removes every \r (carriage return) from the input string. I know (from Kernigham and Ritchie) that a very simple implementation for strcpy is the following

while (*t++=*s++) ;

现在我编译使用gcc(Gentoo的4.5.4 P1.0,饼0.4.7)我的程序4.5.4,它打印此:

Now I compiled my program using gcc (Gentoo 4.5.4 p1.0, pie-0.4.7) 4.5.4 and it prints this:

abcdefghi
jklmnpqr          <-- missing 'o'
stuvwxxyz         <-- doubled 'x'

我想这编译器(实际上它的库)使用了的strcpy 一个非常复杂的程序,我不明白其中的道理。

I suppose this compiler (in fact its library) uses a very sophisticated sequence for strcpy, and I don't understand the reason.

推荐答案

您被警告不要那样做。其原因是,一个字节用于字节拷贝实际上是相当缓慢的,需要大量的循环通过一个串来获得的。编译器可以轻松地优化这个(例如,通过每次复制一个 INT -sized块,或使用一些特定于平台的parallellization。)

You were warned not to do that. The reason is that a byte-for-byte copy is actually quite slow and requires a lot of looping to get through a string. The compiler can optimize this easily (for instance, by copying an int-sized chunk at a time, or using some platform-specific parallellization.)

但是,如果字符串重叠,那么这些优化对您的数据不再有效的假设。这样一来,他们给你不确定的结果。很可能你的旧有的GCC根本没有做任何这样的优化。

But if the strings overlap, then those optimizations make assumptions about your data that are no longer valid. As a result, they give you unspecified results. It is likely your older GCC simply didn't do any such optimizations.

由于对的strcpy()的文档表示,不使用重叠的字符串的

Since the documentation for strcpy() says not to use overlapping strings, don't.

这篇关于strcpy的是如何实现的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆