5

It's almost common knowledge that the code below correctly frees the memory of 100 integers.

int* ip = new int[100];
delete [] ip; 

And I think even for user defined classes it works:

Node* ip = new Node[100];
delete [] ip; 
  1. In the first case, is the size of memory to be freed (400 bytes), determined at compile time? Basically, what goes on internally?

  2. In the second case, will the destructor of Node be called on each of the 100 objects?

Essentially, I have been using this syntax, but never understood what goes on internally and now I am curious.

1
  • 1
    Do use std::vector<>, though, in normal use. Commented May 11, 2011 at 6:25

1 Answer 1

7
  1. No. The memory allocator invisibly keeps track of the size. The size cannot be determined at compile time, because then the allocation would not be truly dynamic and the following would not work:

size_t n;
std::cin >> n;
a = new int[n];
// do something interesting
delete[] a;
  1. Yes. To convince yourself of this fact, try

struct Foo {
    ~Foo() { std::cout << "Goodbye, cruel world.\n"; }
};

// in main
size_t n;
std::cin >> n;
Foo *a = new Foo[n];
delete[] a;
Sign up to request clarification or add additional context in comments.

9 Comments

So is the memory allocator a separate process/thread/module in any compiled C++ program? And who does the job of calling the destructor in case B? Is it the "memory allocator" or does the compiled code has the instructions to call the destructor? Thanks!
The memory allocator is part of the C++ standard library. new and delete[] statements are commonly compiled into calls to functions that wrap malloc and free or an OS-level interface. The destructor is also called by the memory allocator (it's just a function, after all).
Oh okay. Makes sense now. Its surprising how I have been using the syntax for long, assuming it magically works, without giving a thought to it.
So if I dynamically de-allocate an array of 'N' class objects, inside the library de-allocator function, the destructor would be called on each object... sounds fine :)
I'd say that destructors are more likely to be called by compiler-injected code, rather than the memory allocator as part of language support library.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.