复制内存时出现问题

发布于 2024-10-30 16:50:00 字数 580 浏览 0 评论 0原文

所以有一个问题我连续两个晚上都在头疼:

(tuple1 和 tuple2 是传递给这个函数的空指针)

char *data;

data = (char*) calloc (76, 1);
memcpy(data, tuple1, 32);
memcpy(data+32, tuple2, 44);

这个想法是分配内存等于 tuple1 和 tuple1 的大小之和tuple2tuple1 是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怀念你的温柔 2024-11-06 16:50:00

我怀疑对齐和/或填充有问题,tuple1 和 tuple2 的类型声明是什么?

你怎么知道它们的确切尺寸?对事物进行硬编码的代码是可疑的,应该使用 sizeof 而不是幻数文字。

另外,您不应该在 C 语言中强制转换 calloc() 的返回值。

I would suspect issues with alignment and/or padding, what are the type declarations of tuple1 and tuple2?

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.

半﹌身腐败 2024-11-06 16:50:00

从更小的、更容易调试的东西开始你的实验:

void* tuple1 = calloc(2, 1);
char* content1 = "ab";
memcpy(tuple1, content1, 2);

void* tuple2 = calloc(4, 1);
char* content2 = "cdef";;
memcpy(tuple2, content2, 4);

char *data = data = (char*) calloc (6, 1);
memcpy(data, tuple1, 2);
memcpy(data+2, tuple2, 4);

printf("%.*s\n", 6, data); // should print: abcdef

Begin your experiment with something smaller, which is easier to debug:

void* tuple1 = calloc(2, 1);
char* content1 = "ab";
memcpy(tuple1, content1, 2);

void* tuple2 = calloc(4, 1);
char* content2 = "cdef";;
memcpy(tuple2, content2, 4);

char *data = data = (char*) calloc (6, 1);
memcpy(data, tuple1, 2);
memcpy(data+2, tuple2, 4);

printf("%.*s\n", 6, data); // should print: abcdef
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文