问题描述
一位同事遇到了一个有趣的问题。假设我们有这样的C
函数:
void WRITE_THING(void * addr,THING t)
{
memcpy(addr,& t,sizeof t);
}
将THING复制到任何字节地址(可能没有对齐
THING,因此没有做*(THING *)addr = t)。
有一个失败的平台,即在函数之后,addr的内容不是写入它的东西。 (addr是
a malloc''d区域中的地址,因此正确对齐THING)。
使用我们自己的函数:
void MemCopy(void * dest,void * src,size_t sz)
{
unsigned char * t = dest;
unsigned char * s = src;
while(sz--)
* t ++ = * s ++;
}
工作。对我们来说,系统memcpy看起来很破碎。关于
为什么memcpy版本不起作用的任何其他意见?
感谢任何想法,
彼得
A colleague encountered an interesting problem. Suppose we have a C
function like this:
void WRITE_THING(void* addr, THING t)
{
memcpy(addr, &t, sizeof t);
}
to copy a THING to any byte address (which might not be aligned for a
THING, hence not doing *(THING*)addr = t).
There''s a platform on which it fails, i.e. after the function the
contents of addr are not the thing written to it. (addr is an address in
a malloc''d area, hence properly aligned for THING).
Using our own function like this:
void MemCopy(void* dest, void* src, size_t sz)
{
unsigned char* t = dest;
unsigned char* s = src;
while (sz--)
*t++ = *s++;
}
DOES work. To us, the system memcpy looks broken. Any other opinions on
why the memcpy version wouldn''t work?
Thanks for any ideas,
Peter
推荐答案
我不知道为什么它可以不工作......它是唯一的标准C库
功能看起来不起作用吗?
内存的memcpy函数是不是?
另外,如果你将sizeof改为sizeof(t)怎么办?
你是#include< string.h>?
如果你使用gcc,那么'' s相应的asm输出(使用-S开关将
翻译.c源代码转换为asm源代码)。
Alex
I don''t know why it can be not working... Is it the only standard C library
function that looks like not working?
Is the memcpy function inlined or not?
Also, what if you change sizeof t to sizeof(t)?
Do you #include <string.h>?
If you use gcc, what''s the corresponding asm output (use the -S switch to
translate .c source into asm source).
Alex
不会改变任何东西(除非实施严重破坏)
-
Emmanuel
C-FAQ:
C库:
" Mal nommer les choses c''est ajouter du malheur au
monde。 - Albert Camus。
Won''t change anything (unless the implementation is seriously broken)
--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html
"Mal nommer les choses c''est ajouter du malheur au
monde." -- Albert Camus.
陷阱!说实话,我不知道。我没想到要问,假设这位同事知道他在做什么,我会花点b $ b。我将在星期一检查
。
彼得
Gotcha! To be honest, I don''t know. It didn''t occur to me to ask,
assuming that the colleague knew what he was doing. I will have to check
on Monday.
Peter
这篇关于memcpy坏了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!