Having trouble with copying struct to another memo

2019-10-05 14:03发布

问题:

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\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?

回答1:

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.



回答2:

Okay i solved this

basically it was the problem with the pointer that was accessing the malloc'd memory

it was this line that was causing me problems

head * k = (head *)s;

it should have been

 u_int32_t * k = (u_int32_t *)s;


标签: c struct