[dynamic]Arrays... help

I'm trying to build an array of a certain size, after receiving user input. The method I'm trying is
1
2
int var = 3;
int* ar = new int[var];


When doing tests I did this (and it worked) and red flags popped off in my head.

1
2
3
4
5
6
7
8
int var = 3;
int* ar = new int[var];
ar[0] = 0;
ar[1] = 1;
ar[2] = 2;
ar[3] = 3;
ar[4] = 4;
cout << ar[0] << ar[1] << ar[2] << ar[3] << ar[4] << endl;


Can someone explain to me if this method is considered safe, and possibly tell me why I'm not getting stack errors when trying to overload the array?
It certainly isn't considered safe: line 6 and line 7 invoke undefined behavior, anything at all can happen if this program is executed.
Can someone explain to me if this method is considered safe,


It absolutely is not safe. It is causing "heap corruption" which is one of the worst kinds of bugs because it is so very hard to find.

and possibly tell me why I'm not getting stack errors when trying to overload the array?


You're not getting stack errors because your array isn't on the stack. It's on the heap. What's happening is that you are writing to unallocated memory which may or may not be used by other areas of your program.

So by stepping out of bounds of your array like this, you might be "trashing" other variables in your program. This can lead to very strange bugs like variables just having their values magically changed. Or, the memory you're trashing might not be used... in which case you won't be able to notice anything.

But the uncertainty here is exactly why these kinds of bugs are so dangerous and hard to find. Your program might run fine 95% of the time... but then might freak out and do insane things or flat out explode that last 5% of the time. There's no way to know what's going to happen.



So no.. this is not safe.
This is what I was worried about. Thank you disch for the detailed information.

So considering all that, I assume that
1
2
3
4
5
int var = 3;
int* ar = new int[var];
ar[0] = 0;
ar[1] = 1;
ar[2] = 2;

is considered safe, since it does not extend beyond the allocated memory on the heap?
Yes.
This is why you're much better off using std::vector, instead of C-style arrays. All the memory management is done automatically by the class.
vector<int> v(3); v[4]=4; will also compile and result in undefined program. Just don't violate the documented preconditions.
Fair point :)
vector<int> v(3); v[4]=4; will also compile and result in undefined program. Just don't violate the documented preconditions.


but at least you get a sensible runtime error when you try this with a vector.
('vector subscript out of range' or something like that).
Last edited on
but at least you get a sensible runtime error when you try this with a vector.


That's not guaranteed.

You only get that in debug builds, and only in some implementations.
Topic archived. No new replies allowed.