memcpy() 不会停止复制
可能的重复:
复制内存时出现问题
(tuple1和tuple2是传递给这个函数的void指针)
char *data;
data = (char*) calloc (84, 1);
memcpy(data, tuple1, 44);
memcpy(data+44, tuple2, 40);
我已经分配了84数据字节。我正在做第一次内存复制 memcpy(data, tuple1, 44);它将 44 个字节从 tuple1 的地址复制到 data 的地址,当我尝试读取数据时,结果发现它已经在数据的前 44 个字节上复制了 tuple1 的字节,然后再次复制了 tuple1 的 44 个字节直到填满分配给数据的 84 字节。
当我进行第二次内存复制时,我尝试将 tuple2 的 40 字节粘贴到数据地址之后的 44 字节处。实际上,它与 tuple1 执行相同的操作,甚至更多 - 它从数据地址开始粘贴,而不是从数据地址之后的 44 个字节开始粘贴。
这是为什么?!我该如何预防呢?谁来帮帮我吧,我真的很绝望。
Possible Duplicate:
Problem when copying memory
(tuple1 and tuple2 are void pointers passed to this function)
char *data;
data = (char*) calloc (84, 1);
memcpy(data, tuple1, 44);
memcpy(data+44, tuple2, 40);
I have allocated 84 bytes for data. I am doing the first memory copy memcpy(data, tuple1, 44); which copies 44 bytes from the address of tuple1 to the address of data and when I try to read data it turns out that it had copied the bytes of tuple1 on the first 44 bytes of data and then it had copied again the 44 bytes of tuple1 until it has filled the 84 bytes allocated for data.
When I do the second memory copy I try to paste the 40 bytes of tuple2 44 bytes after the address of data. In reality it does the same thing as with tuple1 and even more - it starts pasting from the address of data and not 44 bytes after the address of data.
Why is that?! And how can I prevent it? Anyone help, I'm very desperate.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
tuple1
和tuple2
的定义是什么?它们的尺码至少分别为 44 和 40 吗?它们是否可能与data
指向相同的内存?What are the definitions of
tuple1
andtuple2
? Are they at least of size 44 and 40 (respectively)? Do they perhaps point into the same memory asdata
?如果将数据视为字符串,则可能会缺少空终止符。
您已使用 calloc 将内存初始化为零,但如果您覆盖了每个字节,则没有任何内容可以终止字符串。
If you are treating the data as a string, you may be missing a null terminator.
You have used calloc to initialize the memory to zero but if you have overwritten every single byte there is nothing left to terminate the string.
你应该使用地址。
可能有帮助。
you should use addresses.
may help.