Question: 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?

Answer: 
The above code is [Undefined Behaviour](http://en.wikipedia.org/wiki/Undefined_behavior). It can work, work incorrectly, not work at all, crash, or order pizza through Microsoft Skype. Thou shalt not rely on undefined behavior.
Allocating memory on the heap allows dynamic allocation of a dynamic amount of memory with a dynamic lifetime.

If you want bounds-checking, you can get it through std::vector::at().

> 
> In what cases would assigning value to a non allocated memory location would be dangerous? 
> 
> 
> 

All cases.

> 
> what are the potential ill-affects? 
> 
> 
> 

Unexpected behavior.

> 
> 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?
> 
> 
> 

Depends on the operating system.