Consider:
struct foo { int a; int b; }; void* p = (void*)malloc(sizeof(struct foo)); ((foo*)p)->a; // Do something. free(p); // Is this safe?
Yes.
malloc returns void *
and free takes void *
, so some of your casts are meaningless, and you're always freeing a void *
even if you're starting with some other sort of pointer.
Yes, it's safe. When allocating memory, the runtime library keeps track of the size of each allocation. When you call free(), it looks up the address, and if it finds an allocation for that address, the correct amount of memory is freed (the block that was allocated at that address).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With