Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why allocate memory? (C++)

I am trying to understand memory allocation in C++. A question that comes to my mind is why is it so necessary to allocate memory? And what happens if we use memory without allocating it? Also, I was shocked to see how careless C++ is on memory allocation. If gives free access to memory through arrays with no bounds checking.

int main()
{
int *p = new int[5];
p[1] = 3;
p[11118] = 9;
cout<<p[11118]<<'\n';
}

The above code works, outputs 9.

In what cases would assigning a value to a non allocated memory location be dangerous? What are the potential ill-effects? Is it possible that the memory location I am accessing has been allocated to some other program and assigning a value to it might cause that program to crash/behave in a very unexpected fashion?

like image 788
Nitin Garg Avatar asked May 20 '26 14:05

Nitin Garg


1 Answers

The above code is Undefined Behaviour. It can work, work incorrectly, not work at all, crash, or order pizza through Microsoft Skype. Thou shalt not rely on undefined behavior.

like image 130
Armen Tsirunyan Avatar answered May 23 '26 04:05

Armen Tsirunyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!