I am coding for a project and find some bug, so I write a small program to reproduce and test it, here is the code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct str_a {
int a;
long b;
char buf[10];
};
int main() {
struct str_a *str1 = malloc(sizeof(struct str_a));
printf("%p\n", str1);
strncpy(str1->buf, "hello", sizeof(str1->buf));
free(str1);
struct str_a *str3 = malloc(sizeof(struct str_a));
printf("%p, %s\n", str3, str3->buf);
struct str_a *str5 = malloc(sizeof(struct str_a));
printf("%p, %s\n", str5, str5->buf);
return 0;
}
I am using gcc4.8 and its output is
0x139b010
0x139b010, hello
0x139b040,
here is the problem, the str3->buf is "hello"? I found same problem in my project. I also use gdb to debug it, and I see after free(str1), the str1->buf is still "hello".So I search the online and found this C - freeing structs it says free(testPerson) is enough,so what is the problem, I also test it in vc++ and str3->buf output some garbage value, which I think is right. so why does gcc behave like this