misteryes
misteryes

Reputation: 2287

Can memory be freed if its pointer has changed type?

Given a memory allocation:

struct typeA *p = malloc(sizeof(struct typeA));

and then somewhere, for example, in a function, there are 2 choices:

void func(void *q)
{
     ....
    free(q);
}

void func(void *q)
{
    ....

    struct typeA *pp = (struct typeA *)q;
    free(pp); 
}

Both of them are OK or just the second is OK? Why?

Upvotes: 1

Views: 74

Answers (3)

Jonatan Goebel
Jonatan Goebel

Reputation: 1149

Yes, it is.

As free() is waiting for a void pointer, your compiler will convert your pointer to void * if needed.

Upvotes: 1

md5
md5

Reputation: 23727

struct typeA *pp = (struct typeA *)q;

This typecast is unecessary. Also, free argument's type is a pointer to void. Therefore, the function cannot have any idea of the type of the lvalue which is used to access the object *pp. It just receives a raw pointer.

Upvotes: 1

user1944441
user1944441

Reputation:

Both are ok. free() only cares about the address that is stored in the pointer and that does not change when casting.

Upvotes: 2

Related Questions