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: 
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.
You are writing past to allocated space for array. It invoke **undefined behavior**. In this case anything could happen.