I've been interested lately about the behaviour of malloc
function in C, and i've observed a interesting behaviour. It looks like the first 'out of bounds' value after a malloc turns out to be NULL (or at least, returns something considered false by if
).
Here is an illustration :
int main (){
int i;
double * d_ptr = malloc (10 * sizeof (double)); //malloc 10 double
for (i=0 ; i<10 ; i++){ // initialise them ...
d_ptr[i] = 42;
}
for (i=0 ;i <50 ; i++){ /// loop obviously trying to go out of bounds
if (d_ptr[i]){
printf("i=%d,d[%d]=%f\n",i,i,d_ptr[i]);
}
else {
printf("out of bounds : i=%d\n",i);
break;
}
}
printf("exited 'out of bounds loop' safely\n");
free(d_ptr);
return 0;
}
Here's the output :
i=0,d[0]=42.000000
i=1,d[1]=42.000000
i=2,d[2]=42.000000
i=3,d[3]=42.000000
i=4,d[4]=42.000000
i=5,d[5]=42.000000
i=6,d[6]=42.000000
i=7,d[7]=42.000000
i=8,d[8]=42.000000
i=9,d[9]=42.000000
out of bounds : i=10
exited 'out of bounds loop' safely
My questions are :
Is this behavior predictable ? I tried a bunch of variable types, differents sizes for the malloc, and i always am exiting the loop safely.
If it is predictable, can it become a reliable way to loop on pointers in situation where knowing their 'size' would be tricky, or require lots of rewriting ?
- And finally, what is the deeper explanation of it ? does malloc allocate one word extra after the memory space it was asked to allocate ?