Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...