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

No, modern OSs are designed just to avoid that (for security reasons).  

And you have to allocate memory because, although every process has its own 4GB space (provided by Windows), they all share the same xxGB the user has on his machine. Allocating memory helps the operating system know which applications need more memory and give it only to who need it.  

Why my "hello world" would need the same RAM crysys 2 needs? :P 

**EDIT:**  

Ok, someone misunderstood what I meant. I didn't say it's ok and everyone can do it and nothing will happen. I just said doing this won't harm any extern process. It still is undefined behavior because no one knows what's at p + 11118, but ub doesn't mean "it can order a pizza through skype" nor other "exciting things", at most an access violation, nothing more.