I have created a nested struct called employee. I allocate a space for an employee from heap using malloc. Then, I release the space using free. As far as I know, free function only marks a location available for the future allocation. Hence, the content of allocated memory remains in the memory and it causes heap inspection.
Structs I defined in the beginning of my program as follow.
struct address{
char *city;
int zip;
}
struct employee{
char *name;
struct address add;
}
I implemented a function called sanitize to replace the private fields with junk values (0xAA
in this case). Then, I tested sanitize in the main function.
void sanitize(char *ptr, int size){
memset(ptr, 0xAA, size);
}
int main()
{
struct employee* emp;
emp = malloc(sizeof(char) * 40);
emp->name = "John";
emp->add.city = "London";
emp->add.zip = 221;
printf("%s\n", emp->add.city);
sanitize(&(emp->add), sizeof(struct address));
printf("%s\n", emp->add.city);
return 0;
}
During runtime I get segmentation fault. What is wrong with my program? How and in which order shoul I sanitize nested structs?
Thanks in advance.