Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...