正如对这个问题的回答所指出的那样,编译器(在这种情况下是 gcc-4.1.2,是的,它很旧,不,我不能改变它)可以在它认为合适的地方用 memcpy 替换结构分配。
我在 valgrind 下运行一些代码,并收到有关 memcpy 源/目标重叠的警告。当我查看代码时,我看到了这个(释义):
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
,那么这是一个无效的调用,因为源和目标重叠。
显然,如果我将赋值语句frob
改为调用memmove
,那么问题就消失了。
但这是一个编译器错误,还是该赋值语句在某种程度上无效?