Question: Can someone explain why does this code works, even though i allocate memory only for 2 cells in st array?

```
int main(void){

st=(int *)malloc(sizeof(int)*2);
int j;
for(j=0; j<5; j++){
    st[j]=j*10000;
}
}

```

While the next code won't work...

```
int main(void){

st=(int *)malloc(sizeof(int)*2);
int j;
for(j=0; j<6; j++){
    st[j]=j*10000;
}
for(j=0; j<6; j++)
    printf("st[%d]=%d\n",j,st[j]);
}

```

As i understand, i should not be able to put a number in st[j] for j>1. 

Thanks a lot !!!

Answer: 
Accessing unallocated memory is "undefined behavior". That means the program *can* exit with a runtime error, but it doesn't have to.

Many compilers build code with certain saveguards around allocated memory to cause crashs when writing beyond it, but these don't have to work in *any* condition. In your special case it seems like going 12 bytes over the array boundary doesn't trigger it, but going 16 bytes does. But that's also something you can't and shouldn't rely on. Depending on other circumstances, another program, the same program compiled with other options or even the same program executed at a different time might behave different.
In your first example, the memory you write to is never read again. A standard-compliant compiler that can detect this is allowed to eliminate the code, as long as it behaves identically. Since the program is not required to crash, the compiler can replace it with an empty program.