new - delete

Ok, I've been looking around the internet for this and I'm still not sure.

Say I have the this code:
1
2
3
4
5
6
7
8
int main()
{
	int integer = 5;

	int *blah = new int[ integer ];

	return 0;
}


Now, when my program exits, will anything( The OS etc ) take care of any allocated memory and release it back to the OS?

Also, say I wish to have a function take care of all the cleaning up. The following code compiles and runs, but I can still output the size of a newed variable after deletion?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

void cleanUp( int *blah )
{
	delete[] blah;
}


int main()
{
	int integer = 5;

	int *blah = new int[ integer ];

	cleanUp( blah );

	std::cout << sizeof( blah );

	return 0;
}


Is it not possible to delete in this manner?

Thanks for any info.
Now, when my program exits, will anything( The OS etc ) take care of any allocated memory and release it back to the OS?


From a recent response on the same subject:

The issue is not whether the OS releases the memory or not. All modern protected OSes will release the memory occupied by the program when the program terminates.

The issue is that it's a poor programming practice not to do so. If you get in the habit of being careless about releasing memory in your program, when you tackle more complex programs where there are lots of objects with different lifespans, you will have memory leaks that will be hard to find and difficult to fix.

Consider a threaded program, or a windowed or event driven program where objects are created upon an event. You want to be very sure that the objects (and memory owned by them) are released and do not create memory leaks or your program may crash due to heap exhaustion.


but I can still output the size of a newed variable after deletion?

You're not outputting the size the array that you allocated, but rather the the size of blah, which is an int pointer. sizeof() is known at compile time. It has nothing to do with whether you new'ed or deleted what it points at.
Thanks for the info!! I hardly use new, but when I do, it's in a class, then the dtor takes care of the rest.

I just wanted some more info on it. (:

It's funny, while I was writing this OP, I had a feeling you were going to answer it, Anon! lol.
Topic archived. No new replies allowed.