-2

Please have a look at the following code

#include <iostream>

using namespace std;

class Memory
{
private:
    int *memory;

public:
    Memory()
    {
        memory = new int[3];

        for(int i=0;i<3;i++)
        {
            memory[i] = i;
            cout << memory[i] << endl;
        }
    }

    ~Memory()
    {
        delete[] memory;
    }
};

int main()
{
    cout << "Running" << endl;

    Memory m;
    // do I have to invoke ~Memory() ?

    int *secondMemory = new int[5];
    //How to clear the memory of 'secondMemory' ?

    system("pause");
    return 0;


}

In here, I have cleared the memory of the dynamically allocated memory array in the class's destructor. But my questions are

  1. do I have to invoke ~Memory() ?
  2. How to clear the memory of 'secondMemory' ?

These questions are asked as comments in the appropriate places of the code. Please help!

Edit

The problem here is, if I delete the memory of 'secondMemory' in main(), then the memory is gone as soon as it is allocated!

PeakGen
  • 21,894
  • 86
  • 261
  • 463
  • 3
    @LightnessRacesinOrbit: No, my cat ate it. Why? – PeakGen Apr 05 '13 at 15:21
  • http://stackoverflow.com/q/106508/560648 http://stackoverflow.com/q/8706192/560648 http://stackoverflow.com/q/76796/560648 **http://stackoverflow.com/q/6403055/560648** – Lightness Races in Orbit Apr 05 '13 at 15:22
  • 1
    Why are you worried about `secondMemory` being "gone as soon as it is allocated"? You are not using it anyway... If you were to do something with it, then obviously you would need to perform the release *after* using it. – Luc Touraille Apr 05 '13 at 15:32
  • 1
    @LucTouraille: Thanks for the reply. My mock paper has asked a question in this way. "What happens to the memory if we delete it?" is the question. – PeakGen Apr 05 '13 at 15:36

4 Answers4

11

do I have to invoke ~Memory() ?

No, objects with automatic storage duration (like m) get destroyed when they go out of scope. In other words, the destructor is automatically called by the system. In this case, m gets destroyed upon returning from the main() function.

How to clear the memory of 'secondMemory' ?

Every object allocated with new must be destroyed through a corresponding call to delete, and every array allocated with new[] must be destroyed with a corresponding call to delete[]:

delete[] secondMemory;

Failing to do so results in memory leaks.

However, keep in mind that using raw pointers to perform manual memory management is regarded as a bad programming practice in Modern C++. Rather use standard containers, like std::vector<>, whenever you can.

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
  • ok, but you mean I have to call it just after the memory allocation? I mean, just down the int *secondMemory = new int[5]; ? Then, the memory is allocated, and it is gone within mili seconds! – PeakGen Apr 05 '13 at 15:24
  • @Yohan: You have to deallocate the memory before you lose the last reference to it. In this case, you have to `delete[]` it before you return from `main()` (but you can do it *any time* before returning from `main()`). – Andy Prowl Apr 05 '13 at 15:25
  • Btw, this "Modern C++" style thing consists of using RAII, which is a feature that was already in the language in the 1990s. Yes, it's *that* modern. – R. Martinho Fernandes Apr 05 '13 at 15:26
  • @Andy I've been seeing a lot of claims that this is a bad practice lately. Do you have a definitive source for that? While I agree that it is overused and most cases could be replaced by a standard container, it is still a fundamental part of C++ memory management in general. I feel, especially for someone just learning the language, they should have a clear understanding of how this works before moving on to containers and other advanced concepts like RAII. – Dave Rager Apr 05 '13 at 15:36
  • @DaveRager: I understand what you mean, but I actually see things the other way round. Learners should first get familiar with the higher-level abstractions and concepts that the language and its standard library offer, and only after delve into the low-level details of how those things are implemented, and how to obtain maximum control over memory allocation. – Andy Prowl Apr 05 '13 at 15:39
  • @Yohan Why do you think you have to deallocate the memory right after you've allocated it? What would be the purpose in that? – JBentley Apr 05 '13 at 15:40
  • @JBentley: Thanks for the reply. It is a very good point. hmm... Yes, I have understood it incorrectly.. – PeakGen Apr 05 '13 at 15:42
  • @everyone: Basically, I am a Java programmer. OK, C++ programmer too, but not 'old' as Java. This question has been asked in my degree mock paper. I am practicing the questions and answers, before I face to the real exam :) – PeakGen Apr 05 '13 at 15:45
  • @Yohan: OK, good luck with your exam :) – Andy Prowl Apr 05 '13 at 15:47
  • @AndyProwl: Anyway, after the delete[] I have to do 'memory=0' and 'secondMemory=0' right? To prevent it from re-allocating? – PeakGen Apr 05 '13 at 16:26
  • @Yohan: No, you don't have to. And in any case that wouldn't help preventing reallocation. that would just help figuring out that deallocation has been done (by checking `if (secondMemory == 0)` before possibly dereferencing `secondMemory`). In the case of `memory`, that's not even legal, because `memory` is an object of type `Memory`, not a pointer, so you can't assign zero to it (unless you have an overloaded `operator =`, but that would be non-sense in this case). – Andy Prowl Apr 05 '13 at 16:29
4

do I have to invoke ~Memory()

No, destructors are invoked automatically when the object falls out of scope.

How to clear the memory of 'secondMemory'?

Use delete[] secondMemory;

user229044
  • 232,980
  • 40
  • 330
  • 338
2
 Memory m;
// do I have to invoke ~Memory() ?

No this is not dynamically allocated so the compiler calls the destructor for you when m goes out of scope. In this case when main returns.

int *secondMemory = new int[5];
//How to clear the memory of 'secondMemory' ?

This is allocated dynamically so you have to deallocate it.

delete [] secondMemory;
2

do I have to invoke ~Memory() ?

When the object goes out of scope, ~Memory() will automatically be invoked. So no, you don't have to do anything to invoke it manually.

How to clear the memory of 'secondMemory' ?

Just use

delete [] secondMemory

since you initialized int* secondMemory using new and [].

xcdemon05
  • 1,372
  • 5
  • 25
  • 49