Home > Enterprise >  In C , why can't an object be freed when its pointer is out of scope?
In C , why can't an object be freed when its pointer is out of scope?

Time:11-18

Say I have a method, then new an object inside the method:

void MyMethod() {
  Obj* p = new Obj();
}

When the function ends, the pointer will be dropped because it's out of scope, and if I'm not returning the p pointer, that means there's no reference of this Obj object, why can't the compiler do the object deletion for us?

So there won't be a "memory leak" if people forget to do so.

CodePudding user response:

It can with std::unique_ptr! Raw pointers aren’t really for every-day use in modern C you want this:

#include <memory>

void MyMethod() {
  std::unique_ptr<Obj> p = std::make_unique<Obj>();
   // no leak!
}

Or you can also just do Obj p; but I’m guessing you know that.

CodePudding user response:

Figuring out whether the pointer is or is not going out of scope at compile time is very hard.

Say you have code like this:

void bar(Obj* obj); //we do not know what this method does

int MyMethod() {
  Obj* obj = new Obj();
  bar(obj);
}

Can you delete obj at the end of MyMethod? The answer is no, because bar() might still use it. For example, bar could look like this:

void* someGlobalVariable;

void bar(Obj* obj) {
  someGlobalVariable = (void*) obj;
}

Then MyMethod may not delete the object, because it is still in use from someGlobalVariable. bar() also may not delete the object, because you do not want methods to randomly deallocate memory passed into them when you do not expect it. So the compiler can not help you here, you need to manage the memory yourself.

In general, we want to eventually free all memory we allocate. Since the compiler can not do this for us (at least not always), we need to do it manually. Now, we could design a compiler that has some rules for when it automatically inserts code deleting a pointer.

But such a compiler would be cumbersome to use in practice, because you would always need to remember the rules for when the compiler deletes the memory for you, versus when you need to do it yourself. And if you make the compiler more clever, you make existing programs wrong. So the designers of C picked the consistent option of "you must always free all memory you allocate yourself".

  • Related