Please, what is this program doing and how to get some of it be seen?


using namespace std;

int main(){
int * a=new int [10];
return 0;
The program is allocating a dynamic array of integers then using assert to check if the pointer that is pointing to them is not null.

Of course, it isn't - you've just done the assignment in the previous line. If the expression in the assert is false, the program would terminate. In this case it doesn't because it's true as a isn't null.

I'm not sure what you mean by get some of it seen. You're not printing anything to the screen, so you'd need to do that in order for anything to be output. Also, though you've allocated the memory and assigned to the pointer, the array itself contains nothing but junk values. You'd probably want to put something more meaningful in there.

Finally, you have a memory leak. Don't forget that whenever you allocate with new you must always free up with delete unless you make use of smart pointers.
isn't new throws instead std::bad_alloc if memory allocation fails ? and not set the pointer to NULL ?

if my statement is correct, then you should use int* a = new (std::nothrow) int[ 10 ] ; instead
Real question: I did it in codepad. What happened (I mean, WITHOUT DELETE!;))

No idea, because it is online.

p.s.. So, we can use some asserts in certain cases as "breaks"?
Last edited on
Nothing too catastrophic in this example. The application is short and there's a strong chance that the OS will free up the memory when your program ends. I think an older OS may not have done this, meaning that there'd be system memory that couldn't be accessed after your program has executed.

It's good practice, though and on bigger, more memory-intensive programs it's important to manage your memory.

Alternatively, as I hinted in my first post, people make use of smart pointers, which will handle their own deallocation.

enemy wrote:
So, we canuse some asserts incertain cases as "breaks"?

I wouldn't say so, no. If you think about a break, you can use it to jump out of something like a loop. Your program doesn't terminate.
Last edited on

So, we can use some asserts in certain cases as "breaks"?

break is keyword to exit from a loop. assert is a function to test whether there's an error on the expression or not

Haha , I did not mean we SHOULD, I just ment we COULD;)
Topic archived. No new replies allowed.