struct foo
{
int a;
int b;
};
void* p = (void*)malloc(sizeof(struct foo));
((foo*)p)->a;//do something.
free(p);//Is this safe?
thanks!
struct foo
{
int a;
int b;
};
void* p = (void*)malloc(sizeof(struct foo));
((foo*)p)->a;//do something.
free(p);//Is this safe?
thanks!
Yes. Why wouldn't it be?
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 -- free
takes a pointer to void, so when you call it, the pointer is (implicitly) cast to a pointer to void in any case.
The rest of your code isn't quite so safe:
void* p = (void*)malloc(sizeof(foo));
You should not cast the return from malloc (in C). This can cover up the mistake of forgetting to #include <stdlib.h>
Yes. The function prototype for free
is even:
void free(void *ptr);
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).
Perhaps it doesn't feel safe because of the magic happening behind the scenes. The C runtime and/or the OS itself is actively tracking the memory returned by malloc including its size and location. See though it feels like you are passing a typeless pointer back to free(), you in fact passing back a reference to an object the memory manager is actively tracking.
in C it is perfectly safe because there are no destructors to call.
the memory system keeps track of they size of allocations.
in c++ you must delete the same type you new, including using the delete[] operator to delete new'ed arrays.
this is just to make sure destructors are called.