why does the 4 remain after free() ?
Because pet1 was not freed, and so now points to where pet2 did. Since pet1 was not allocated anything and pet2 was freed, this memory can be overwritten, but has not been because nothing else has happened. For example, with my compiler if I add the following:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
main( )
{ struct animal
{ char name[25];
char breed[25];
int age;
} *pet1, *pet2, *pet3;
char *this;
pet2 = malloc(sizeof(struct animal));
strcpy(pet2->name,"Krystal");
strcpy(pet2->breed,"German Shepard");
pet2->age = 4;
/* now print out the data described above */
printf("%s is a %s, and is %d years old.\n",pet2->name,pet2->breed, pet2->age);
pet1 = pet2; /* pet1 now points to the same structure that pet3 points to */
free(pet2); /* this frees up one structure */
pet3=malloc(sizeof(struct animal));
strcpy(pet3->name,"Ecstacy");
strcpy(pet3->breed,"Golden Lab");
printf("%s is a %s, and is %d years old.\n",pet1->name,pet1->breed, pet1->age);
printf("pet3 age=%d\n",pet3->age)
}
The output is:
Krystal is a German Shepard, and is 4 years old.
Ecstacy is a Golden Lab, and is 4 years old.
pet3 age=4
pet1 (mysteriously and apparently) now points to pet3, and pet3 apparently has inherited pet2's age! This is beacause pet3 is stored in the same physical location as pet2 was -- the memory was freed for other use, not erased -- and pet1 still points to this location.
However, there is no guarantee the compiler (linker?) will actually do that, so it's not a technique to be used in programming.