Why is this code working? Even if, I am allocating only 1 int's space using malloc ? In such case answer in undefined behavior.
Allocating block of 4
bytes like
int *a = (int *)malloc(sizeof(int)); /* No need to cast the malloc result */
and accessing beyond that like
a[i] = i; /* upto i<1 behavior is guaranteed as only 4byte allocated, not after */
results in undefined behavior i.e anything can happen and you shouldn't depend on it doing the same thing twice.
Side note, type casting the result of malloc()
is not required as malloc()
return type void*
& its automatically promoted safely into required type. Read Do I cast the result of malloc?
And always check the return value malloc()
. for e.g
int *a = malloc(sizeof(int));
if( a != NULL) {
/* allocated successfully & do_something()_with_malloced_memory() */
}
else {
/* error handling.. malloc failed */
}