L
lawtrevor
I have a question regarding the use of free() based on some code I need
to decipher:
{
struct A {<A fields>};
struct B {<A fields> + <Bfields>};
typedef struct A Aobj;
typedef struct B Bobj;
Aobj *ptrToA = (struct A*) calloc(1,sizeof(struct B));
free(ptrToA);
}
Will this free the entire memory block of size sizeof(struct B), or
only a block starting at ptrToA of size sizeof(struct A)? The posts I
have read strongly suggest this will, as probably intended, free the
entire block produced by calloc(), but in those posts it seems
sizeof(Aobj) == N*sizeof(Bobj), i.e. the size of the allocated block is
an integer multiple of the dereferenced type of the pointer to which
the allocated block's void pointer is cast (Don't know how to express
this well). Such would be the case when allocating a single instance
of an object or an array of the same objects on the heap. Just want to
make sure what is done above is safe (assuming the type interpretation
of the allocated block elsewhere is correct.)
Thank you for your time.
to decipher:
{
struct A {<A fields>};
struct B {<A fields> + <Bfields>};
typedef struct A Aobj;
typedef struct B Bobj;
Aobj *ptrToA = (struct A*) calloc(1,sizeof(struct B));
free(ptrToA);
}
Will this free the entire memory block of size sizeof(struct B), or
only a block starting at ptrToA of size sizeof(struct A)? The posts I
have read strongly suggest this will, as probably intended, free the
entire block produced by calloc(), but in those posts it seems
sizeof(Aobj) == N*sizeof(Bobj), i.e. the size of the allocated block is
an integer multiple of the dereferenced type of the pointer to which
the allocated block's void pointer is cast (Don't know how to express
this well). Such would be the case when allocating a single instance
of an object or an array of the same objects on the heap. Just want to
make sure what is done above is safe (assuming the type interpretation
of the allocated block elsewhere is correct.)
Thank you for your time.