Search code examples
c++pointersstructnullfree

C++: properly freeing a pointer to a struct


So I am trying to learn C++ (and a little bit of C) and was wondering if there is a truly proper way to free a pointer to a struct. There is an example of what I am talking about below.

#include <iostream>

struct guy {
  int the_data;
};

int main() {
  guy the_guy, *ptr;

  ptr = &the_guy;
  ptr->the_data = 3;
  ptr = NULL;
  free(ptr);
  std::cout << "whaddup guy's data: " << the_guy.the_data <<std::endl;
}

I'm mostly curious because I have seen answers that say you need to set the pointer to NULL after you free it? This can't be right because whenever I try that I get an error at compile time.

Thoughts?


Solution

  • guy the_guy here is a local variable which lifetime is defined by its scope! Free memory of local variable is just Undefined Behavior and you are lucky that it crashes.

    free can be used only on memory which was allocated by malloc (or calloc or realloc). In all other cases it will lead to undefined behavior, so do not do it.