You cannot partially free the malloc
ed memory; for each malloc
there must be exactly one free
to free the memory (and it is then freed completely). Indeed, giving free
an argument other than the same pointer returned by malloc
or one of the other allocating functions is undefined behaviour.
Also, malloc
and free
don't have any knowledge of how you use the memory, so they don't know that you've decided to put an array of struct coin
in it. malloc
just gives you a pointer to an area of memory large enough to hold the number of bytes you requested, how you use them is up to you.
Use a linked list of, or an array of pointers to, individually allocated structs if you need to manage them individually. That is, use a separate malloc
call to allocate every element in the list or array – note that you must also free
them all individually, and each exactly once.
Edit: You changed the question to show realloc
instead of malloc
. However, the same applies here; you can only free
the pointer returned by realloc
, not a part thereof, nor does free
(or realloc
) know that you are using the memory for an array of structs. Since you are now calloc
ing each data
individually, you can (and indeed must) free
that part individually, but you cannot free
part of the realloc
'ed array – you need to clean it up manually after free
ing the data
element.