复制内存时出现问题
所以有一个问题我连续两个晚上都在头疼:
(tuple1 和 tuple2 是传递给这个函数的空指针)
char *data;
data = (char*) calloc (76, 1);
memcpy(data, tuple1, 32);
memcpy(data+32, tuple2, 44);
这个想法是分配内存等于 tuple1 和 tuple1 的大小之和tuple2
(tuple1
是 32 个字节,tuple2
是 44),然后复制 tuple1
的 32 个字节并粘贴它们在数据地址处,然后复制 tuple2
的 44 字节并将它们粘贴到数据地址后的 32 字节处。
问题是,如果我只复制 tuple1
或仅 tuple2
它确实被复制到了它应该在的地方(我打印的数据太长了,无法放在这里),但是当我执行两个内存复制时,第一个 memcpy()
工作正常,但第二个则不行。
谁能帮我解决这个严重的问题吗?
So there is a problem I am headbanging over two nights in a row:
(tuple1 and tuple2 are void pointers passed to this function)
char *data;
data = (char*) calloc (76, 1);
memcpy(data, tuple1, 32);
memcpy(data+32, tuple2, 44);
The idea is to allocate memory equal to the sum of the sizes of tuple1
and tuple2
(tuple1
is 32 bytes and tuple2
is 44) and then copy the 32 bytes of tuple1
and paste them at the address of data and after that copy the 44 bytes of tuple2
and paste them 32 bytes after the address of data.
The thing is if I copy only tuple1
or only tuple2
it is really copied where it is supposed to be (I am printing data with way too long function to put here), but when I do the two memory copies the first memcpy()
works fine but the second doesn't.
Can anyone help me with this serious problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我怀疑对齐和/或填充有问题,tuple1 和 tuple2 的类型声明是什么?
你怎么知道它们的确切尺寸?对事物进行硬编码的代码是可疑的,应该使用
sizeof
而不是幻数文字。另外,您不应该在 C 语言中强制转换
calloc()
的返回值。I would suspect issues with alignment and/or padding, what are the type declarations of
tuple1
andtuple2
?How do you know their exact sizes? Code that hardcodes things is suspect, there should be some use of
sizeof
rather than magic number literals.Also, you shouldn't cast the return value of
calloc()
, in C.从更小的、更容易调试的东西开始你的实验:
Begin your experiment with something smaller, which is easier to debug: