Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 views
in Technique[技术] by (71.8m points)

c - Having trouble with copying struct to another memory location with memcpy()

Okay so basically I am not sure what is happening here

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

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

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
", &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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...