advanced patterns with `malloc` and `memcpy` leading to corrupted data in C
I've looked through the documentation and I'm still confused about I recently switched to I'm experimenting with Can someone help me understand I'm stuck on something that should probably be simple... I'm working with an scenario where I'm using `malloc` to allocate memory for a structure and then using `memcpy` to copy data into it. However, after the copy, the data seems corrupted when I try to access it later. I'm on GCC 11.2.0 and this is on a Linux system. My code looks something like this: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { int id; char name[30]; } Person; int main() { Person *person = (Person *)malloc(sizeof(Person)); if (person == NULL) { perror("Failed to allocate memory"); return 1; } Person temp; temp.id = 123; strcpy(temp.name, "John Doe"); memcpy(person, &temp, sizeof(Person)); // Free temp if it's dynamically allocated (it's not, but if it were...) // free(&temp); printf("ID: %d, Name: %s\n", person->id, person->name); free(person); return 0; } ``` When I run the program, I get the expected output: ``` ID: 123, Name: John Doe ``` However, if I change the allocation to use a larger `sizeof` for `Person` or modify the structure definition later on, I sometimes encounter a segmentation fault or garbage values when I access the `person` structure. I've tried checking if `malloc` returns NULL and ensured I'm copying the right amount of data with `memcpy`. I've also verified that I'm not accessing any out-of-bounds memory, yet the scenario continues when I add more fields to the `Person` struct. Am I missing something about the memory allocation or `memcpy` usage? Why does the data corruption happen when I modify the structure? My development environment is macOS. This is part of a larger service I'm building. How would you solve this? I appreciate any insights! I'm coming from a different tech stack and learning C. Cheers for any assistance!