Вопрос

My first question is does the memory allocated by new in a function gets automatically deleted(deallocated) when the function ends.

int* foo()
{
    int *a = new int;  //memory allocated for an int
    *a = 3;
    return (a);
}//function ends -- is memory for integer still allocated.

If the memory is de-allocated automatically after the function ends, then shouldn't my next code give some error relating to accessing the memory which does not belong to me.

int main()
{
    int *x = foo();
    cout<<*x;
}
Это было полезно?

Решение

No it certainly does not. Every new has to be balanced with a delete. (And, to avoid any future doubt, any new[] has to be balanced with a delete[]).

There are constructs in C++ that will allow the effective release of memory once a container object has gone out of scope. Have a look at std::shared_ptr and std::unique_ptr.

Другие советы

No, the memory is not deallocated.

You should deallocate it manually with delete a;

In languages like Java or C# there is a so called Garbage Collector that handles memory deallocation when it finds out that some data is not longer needed. Garbage Collection can be used with C++, but it's not standard and in practice rarely used.

There are, however, other mechanisms you could use to automate deallocation of memory. Shared pointers are one of them. They introduce additional overhead. In regular C++ code usually the programmer is responsible for managing the memory (allocating and deallocating) manually. For beginners it's important to learn the basics before switching to more advanced mechanisms.

This is a bad practice to allocate dynamically from within a function and depend on the mercy of some other function to deallocate. Ideally, the caller should allocate space, pass that to the calling function and caller would deallocate when not in use.

void foo(int * a)
{
    // a is pre-allocated by caller
    *a = 3;
}//function ends -- caller takes care of allocation and deallocation

int main()
{
    int *x = new int; // memory allocated for an int by caller
    foo(x); // pass x as argument
    cout << *x;
    delete x; // deallocate, not required any more
    return 0;
}

No, it is your responsibility to procure deallocation:

int *i = new int;
delete i;

However, the above code will sooner or later evolve into something that is almost impossible to make exception-safe. Better do not use pointers at all, or if you really must, use a smart pointer which will free the memory for you at the right moment:

std::shared_ptr<int> i (new int);
*i = 0xbeef;
return i;

There exist other smart pointers with different ownership semantics.

For most real world application, any imposed or assumed overhead introduced by smart pointers usually gets weight up easily against more expensive (I really mean money-saving) stuff like maintainability, extensibility, exception safety (where all there intermix into the other two).

Never forget that there exist alternatives to pointers, depending on the situation:

  • standard containers: If you need things like array
  • smart pointers: If you really need a pointer
  • references: Which you cannot forget to deallocate
  • plain objects: No pointers at all. Rely on copying and moving, which usually makes for a high degree of maintainability, extensibility, exception safety and performance. In C++, this should be your default choice.

As above, no raw pointers are never automatically deleted. This is why we don't use raw pointers for controlling lifetimes. We use smart pointers.

Here's your code snippet written correctly in modern c++:

std::unique_ptr<int> foo()
{

    return std::unique_ptr<int>(new int(3));
    // or std::make_unique<int>(3) for c++14

    // function will either std::move the unique_ptr or emplace it efficiently
}

int main()
{
  // x will either be created in-place or move-constructed by foo()
  std::unique_ptr<int> x = foo();

  // potential bug! pointers can be null
  if (x) {
    std::cout << *x;
  }
  else {
    std::cout << "x is null\n";
  }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top