Reputation: 145
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 !!!
Upvotes: 0
Views: 84
Reputation:
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.
Upvotes: 1
Reputation: 69663
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.
Upvotes: 4
Reputation: 106012
You are writing past to allocated space for array. It invoke undefined behavior. In this case anything could happen.
Upvotes: 0