Okay, so i was experimenting with pointers in C++, as i have started to code again after almost an year and a half break(School Stuff). So please spare me if this seems naive to you, i am just rusting off.
Anyways, i was screwing around with pointers in VS 2019, and i noticed something that started to bug me.
This is the code that i wrote:
#include <iostream>
int main() {
int* i = new int[4];
*i = 323;
*(i + 1) = 453;
std::cout << *i << std::endl;
std::cout << *(i + 1) << std::endl;
delete i;
}
Something seems odd right? Dont worry, that delete is intentional, and is kindof the point of this question. Now I expected it to do some memory mishaps, since this is not the way we delete an array on the heap, BUT to my surprise, it did not(I did this in both Debug and Release and had the same observation)
Now i was expecting some sort of mishap at delete, since i did not delete it the way it is supposed to be deleted. BUT
Deleting Incorrectly
Now on another run i actually used the delete operator correctly and it did the same thing:
Now i got the same results when i tried to allocate with malloc and use delete to free it.
So my question is - Why does my code not mess up? I mean if this is how it works, I could just use delete (pointer) to wipe the entire array.
The gist of my question is "What does new operator do under the hood?"
What happens on allocating with “new []” and deleting with just “delete”
The behaviour of the program is undefined.
Now I expected it to do some memory mishaps
Your expectation is misguided. Undefined behaviour does not guarantee mishaps in memory or otherwise. Nothing about the behaviour of the program is guaranteed.
I mean if this is how it works
This is how you observed it to "work". It doesn't mean that it will necessarily always work like that. Welcome to undefined behaviour.