0

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

  • 3
    What do you expect free() to do? Clear the buffer? That is not its job. – Yunnosch Jun 17 '17 at 05:30
  • Compare here https://stackoverflow.com/questions/1119134/how-do-malloc-and-free-work – Yunnosch Jun 17 '17 at 05:32
  • 1
    I don't think I ever closed a question providing 4 (actually more) duplicates... This is probably on the same frequency as the usual `i += i + ++i` sequence point questions. – Matteo Italia Jun 17 '17 at 05:35

0 Answers0