遇到问题与结构复制到另一个存储单元中的memcpy() [英] Having trouble with copying struct to another memory location with memcpy()

查看:92
本文介绍了遇到问题与结构复制到另一个存储单元中的memcpy()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,所以基本上我不知道这里发生了什么。

Okay so basically I am not sure what is happening here

我基本上想复制我,而我用malloc分配另一个存储器复制存储器位置定义的结构体变量

I am basically trying to copy a struct variable that I defined to another memory location which I malloc'd using memcopy

编译器不提供任何错误和警告

the compiler does not give any errors and warnings

但是当我试图访问malloc分配内存位置看,如果数据被复制,我发现一些奇怪的号码来了,当我取消引用指针,而不是价值,我复制

however when I try to access the malloc'd memory location to see if the data was copied,I find some weird numbers coming up when I dereference the pointer and not the values that I copied

这是我的code,究竟是什么,我很想念这里,

here is my code , what is it exactly that I am missing here,

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <stdint.h>

typedef uint32_t u_int32_t;

typedef unsigned char byte;
typedef u_int32_t link;
typedef u_int32_t size;
typedef u_int32_t addr;

typedef struct header {
   u_int32_t unkno;  
   size sze;     
   link next;     
   link prev;     
} head;

int main(){

   head x;

   printf("%d %d %d %d\n", &x, &x.unkno,sizeof(head),0x12345);

   x.unkno = 0x12345;
   x.sze = 10;
   x.next = 2;
   x.prev = 6;

   void * s = malloc(sizeof(u_int32_t)*100);

   memcpy(s, (const void *)&x, sizeof(head));

   head * k = (head *)s;

   printf("%d",*(k+1));

   return 0;
}

所以,如果有人可以点我什么,我做错了,或者这是否可能?

so if somebody can point me to what I am doing wrong, or if this is even possible?

推荐答案

您只复制有一个的结构,所分配的400个字节,而的malloc 以任何方式不初始化的内存。

You only copy one structure to the 400 bytes you allocated, and malloc does not initialize the memory in any way.

新分配的内存从的malloc 的内容是的不确定的,并从未初始化的内存读取导致的未定义行为

The contents of newly allocated memory from malloc is indeterminate, and reading from the uninitialized memory leads to undefined behavior.

此外,当你做 *(K + 1)你把 K 为一个数组,以及访问的第二的元素( *(K + 1)等同于 K [1] ) 。然后,你做的东西更加古怪和打印值作为一个十进制数,它实际上不是。

Also, when you do *(k + 1) you treat k as an array, and accessing the second element (*(k + 1) is equivalent to k[1]). You then do something even weirder and print the value as a decimal number, which it really isn't.

最后,打印使用指针时, 的printf 你应该使用%p格式说明。

Lastly, when printing a pointer using printf you should use the "%p" format specifier.

要真正的答案的你的问题,然后是你复制的数据是存在的,在分配内存的开始。你只是不打印任何它。

To actually answer your question, then yes the data you copy is there, at the beginning of the allocated memory. You just don't print any of it.

这篇关于遇到问题与结构复制到另一个存储单元中的memcpy()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆