memcpy与C中的赋值-应该是记忆吗? [英] memcpy vs assignment in C -- should be memmove?

查看:116
本文介绍了memcpy与C中的赋值-应该是记忆吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该问题的答案中指出,编译器(在此case gcc-4.1.2,是的,它已经很旧了,不,我不能更改它)可以在认为合适的地方用memcpy替换结构分配.

As pointed out in an answer to this question, the compiler (in this case gcc-4.1.2, yes it's old, no I can't change it) can replace struct assignments with memcpy where it thinks it is appropriate.

我正在valgrind下运行一些代码,并收到有关memcpy源/目标重叠的警告.当我查看代码时,我看到以下内容(解释):

I'm running some code under valgrind and got a warning about memcpy source/destination overlap. When I look at the code, I see this (paraphrasing):

struct outer
{
    struct inner i;
    // lots of other stuff
};

struct inner
{
    int x;
    // lots of other stuff
};

void frob(struct inner* i, struct outer* o)
{
    o->i = *i;
}

int main()
{
    struct outer o;

    // assign a bunch of fields in o->i...

    frob(&o.i, o);
    return 0;
}

如果gcc决定用memcpy替换该分配,则该调用无效,因为源和目标重叠.

If gcc decides to replace that assignment with memcpy, then it's an invalid call because the source and dest overlap.

很显然,如果我将frob中的赋值语句更改为调用memmove,那么问题就消失了.

Obviously, if I change the assignment statement in frob to call memmove instead, then the problem goes away.

但这是编译器错误,还是该赋值语句某种程度上无效?

But is this a compiler bug, or is that assignment statement somehow invalid?

推荐答案

我认为您正在混淆各个级别. gcc完全可以通过调用任何喜欢的库函数来代替赋值操作,只要它可以保证正确的行为即可.

I think that you are mixing up the levels. gcc is perfectly correct to replace an assignment operation by a call to any library function of its liking, as long as it can guarantee the correct behavior.

这不是调用" memcpy,也不是标准意义上的任何东西.它只是在其库中使用一个函数,因此它可能具有其他保证正确性的信息.标准中描述的memcpy属性是被视为程序员接口的属性,而不是编译器/环境实现程序的接口.

It is not "calling" memcpy or whatsoever in the sense of the standard. It is just using one function it its library for which it might have additional information that guarantees correctness. The properties of memcpy as they are described in the standard are properties seen as interfaces for the programmer, not for the compiler/environment implementor.

所讨论的实现中的memcpy是否实现了使其对赋值操作有效的行为是另一个问题.检查代码甚至检查代码都不难.

Whether or not memcpy in that implementation in question implements a behavior that makes it valid for the assignment operation is another question. It should not be so difficult to check that or even to inspect the code.

这篇关于memcpy与C中的赋值-应该是记忆吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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