b[8]
in the second printf
call accesses memory which is not allocated and invokes undefined behaviour. That's what basically undefined behaviour means. The result is unpredictable. It might seem to be working fine but the next time it may, very well, crash. There are few other things to consider here -
malloc
can fail to allocate memory so checking its return value with theassert
macro is wrong.assert
should be used to debug impossible or wrong code like accessing an array out of its bound.You should not cast the result of
malloc
. Do I cast the result of malloc?realloc
may fail to reallocate a memory block likemalloc
. When it fails, it returnsNULL
and leaves the older block unchanged. This means you would lose handle on the older memory block causing it to leak. You should store the pointer to the older block in a variable before callingrealloc
.