Im simply trying to copy one struct to another (copy by value, NOT by reference). Here is fully working code
/* memcpy example */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE (80*sizeof(char))
typedef struct {
char* name;
} person;
int main ()
{
person p1;
p1.name = (char*) malloc( SIZE );
person p2;
p2.name = (char*) malloc( SIZE );
// set p1
strcpy(p1.name, "John");
// copy p1 > p2
memcpy ( &p2, &p1, SIZE );
printf ("p1.name: %s (%u)\n", p1.name, &p1.name );
printf ("p2.name: %s (%u)\n", p2.name, &p2.name );
// change p1 only
printf("Changing p1.name\n");
strcpy(p1.name, "ONLY p1.name Changed");
// now, why did p2 change?
printf ("p1.name: %s (%u)\n", p1.name, &p1.name );
printf ("p2.name: %s (%u)\n", p2.name, &p2.name );
free(p1.name);
free(p2.name);
return 0;
}
Here is a fiddle http://cpp.sh/57skb
That code outputs
p1.name: John (0x791b3cdd6270)
p2.name: John (0x791b3cdd6280)
Changing p1.name
p1.name: ONLY p1.name Changed (0x791b3cdd6270)
p2.name: ONLY p1.name Changed (0x791b3cdd6280)
Expected output would be
p1.name: John (0x791b3cdd6270)
p2.name: John (0x791b3cdd6280)
Changing p1.name
p1.name: ONLY p1.name Changed (0x791b3cdd6270)
p2.name: John (0x791b3cdd6280)
Question: why does p2 change?
Note that doing the same thing without struct works as expected: http://cpp.sh/6qevd