Generalized function for deallocating and setting pointer to NULL

R

rocco.rossi

I've been trying to write a function capable of checking if a pointer
value is set to NULL, and if it isn't, of deallocating and setting
it's value to NULL regardless of the pointer's type. I thought "void
** " should do the trick, but I kept getting the following warning
message from gcc:

warning: passing argument 1 of 'free_var' from incompatible pointer
type

which obviously could be solved by doing an explicit cast to (void **)
in the argument list when calling the fuction. That however would put
an extra burden on the programmer, so I invented the following
solution which works quite well apparently. Please give me your
opinions on this issue.

void free_var(void *vptr)
{
void **ptr = (void **) vptr;

if (ptr != NULL) {
if (*ptr != NULL) {
free(*ptr);
*ptr = NULL;
}
}
}

Thank you.
 
S

santosh

I've been trying to write a function capable of checking if a pointer
value is set to NULL, and if it isn't, of deallocating and setting
it's value to NULL regardless of the pointer's type. I thought "void
** " should do the trick, but I kept getting the following warning
message from gcc:

warning: passing argument 1 of 'free_var' from incompatible pointer
type

That's because in C the only pointer type capable of pointing to any
type of data is the void *, not a void **. void ** can only point to a
void * data type.
which obviously could be solved by doing an explicit cast to (void **)

Not solved, merely suppressed.
in the argument list when calling the fuction. That however would put
an extra burden on the programmer, so I invented the following
solution which works quite well apparently. Please give me your
opinions on this issue.

void free_var(void *vptr)
{
void **ptr = (void **) vptr;

if (ptr != NULL) {
if (*ptr != NULL) {
free(*ptr);
*ptr = NULL;
}
}
}

C's pass by value convention means that this function does not actually
operate on the caller's 'vptr', merely this function's localised copy.
So the caller's 'vptr' is left indeterminate after a call to this
function.
 
T

Tomás Ó hÉilidhe

rocco.rossi:
I've been trying to write a function capable of checking if a pointer
value is set to NULL, and if it isn't, of deallocating and setting it's
value to NULL regardless of the pointer's type. I thought "void ** "
should do the trick, but I kept getting the following warning message
from gcc:


void DeallocateAndNullify(void **const pp)
{
free (*pp);

*pp = 0;
}

Passing a null pointer to free has no effect, so there's no need to check
it for null.

You could use macros to pretend that C has "pass by reference", but I
wouldn't suggest it -- because a C programmer assumes their object won't
get altered unless they pass its address.
 
C

Charlie Gordon

Tomás Ó hÉilidhe said:
rocco.rossi:


void DeallocateAndNullify(void **const pp)
{
free (*pp);

*pp = 0;
}

Passing a null pointer to free has no effect, so there's no need to check
it for null.

You are right about free(NULL). But your solution is what the OP tried
first and it is not portable because pointer to different types don't all
have the same representation. It means that void ** may not be
inappropriate to store the address of an int *. gcc will give you a warning
if you invoke DeallocateAndNullify(&intp) with int *intp;

You may wonder why in hell C has such constraints... Well most
architectures have a single representation for pointers, and a simple cast
such as DeallocateAndNullify((void**)&intp) will kill the warning but not
cause undefined behaviour. It is utmostly ugly, and you will be tempted to
hide it in a macro, but beyond ugliness, it is error-prone:
DeallocateAndNullify((void**)intp) will go uncaught because you told the
compiler to shut up.

Solutions to this problem are cumbersome, and the one proposed by the OP,
while elegant, has the shortcoming of not catching missing & operators.

It is a major pain that pointers not have a consistent representation, and
the architectures that require extra information for some types are not so
numerous these days. It is actually rather counter productive to encourage
the hardware guys in this direction by keeping support for them.
You could use macros to pretend that C has "pass by reference", but I
wouldn't suggest it -- because a C programmer assumes their object won't
get altered unless they pass its address.

The problem is indeed when the programmer will forget the & operator.
 
J

James Kuyper

I've been trying to write a function capable of checking if a pointer
value is set to NULL, and if it isn't, of deallocating and setting
it's value to NULL regardless of the pointer's type. I thought "void
** " should do the trick, but I kept getting the following warning
message from gcc:

warning: passing argument 1 of 'free_var' from incompatible pointer
type

which obviously could be solved by doing an explicit cast to (void **)
in the argument list when calling the fuction. That however would put
an extra burden on the programmer, so I invented the following
solution which works quite well apparently. Please give me your
opinions on this issue.

void free_var(void *vptr)
{
void **ptr = (void **) vptr;

if (ptr != NULL) {
if (*ptr != NULL) {
free(*ptr);
*ptr = NULL;
}
}
}

That method will work if you use it as follows:

void *vp = malloc(42);
free_var(&vp);

However, the more typical use of malloc is not guaranteed to work:

int *ip = malloc(42*sizeof(int));
free(&ip); // WRONG

This is because the *ptr expression in free_var has defined behavior
only if the pointed-at pointer actually has the type void*. On many
implementations, all pointers have the same representation, so this cast
happens to work. However, the standard allows each pointer type to have
it's own representation (with certain exceptions that aren't relevant here).

The void* type allows a certain amount of genericity in C, but not
enough to implement this idea as a C function. For this kind of
genericity, you need a macro:

#define FREE_VAR(p) (free(p), (p)=NULL)
 
C

CBFalconer

Charlie said:
You are right about free(NULL). But your solution is what the OP
tried first and it is not portable because pointer to different
types don't all have the same representation. It means that
void** may not be inappropriate to store the address of an int*.
gcc will give you a warning if you invoke
DeallocateAndNullify(&intp) with int *intp;

No, you can pass that routine any pointer address, and it will be
auto-converted to void**. After that the free will work
correctly. Also, since void** is a pointer to void*, the NULL
assignment works. But it is more clearly written using NULL rather
than 0.
 
J

jameskuyper

CBFalconer said:
No, you can pass that routine any pointer address, and it will be
auto-converted to void**. After that the free will work
correctly. Also, since void** is a pointer to void*, the NULL
assignment works. But it is more clearly written using NULL rather
than 0.

I'm curious - if sizeof(void*) == 6 and sizeof(int*) == 4, how does
that work? Naively, I'd have expected *pp=0 to attempt to set two
extra bytes that aren't actually part of intp.
 
K

Keith Thompson

CBFalconer said:
No, you can pass that routine any pointer address, and it will be
auto-converted to void**. After that the free will work
correctly. Also, since void** is a pointer to void*, the NULL
assignment works. But it is more clearly written using NULL rather
than 0.

No, you can't. There is no implicit conversion to or from type
void**; there are only implicit conversions to and from type void*,
which is a distinct type.

void* is a generic pointer type. C has *no* generic
pointer-to-pointer type. Something of type void** points to an object
of type void*, and to nothing else.

One way to do what the OP wants is to use a macro, such as;

#define DEALLOCATE(p) (free(p), (p) = NULL)

This fails if the argument is an expression with side effects; the
uppercase name is a hint to avoid calling it with such an argument.

Another way is simply to set the pointer to NULL after freeing it:

free(p);
p = NULL;

or even:

free(p); p = NULL;

(The latter makes it clearer that the two statements are associated,
if you don't mind occasionally putting two statements on one line.
Possibly this could cause problems for debuggers.)

It's easy to forget to set the pointer to NULL after freeing it, but
it's also easy to forget to use DEALLOCATE() rather than free(). But
if you always want to use DEALLOCATE() rather than free(), you can
search your source code for calls to free().

Note that this will prevent some errors, but by no means all of them.
(Actually it doesn't so much prevent errors as make them easier to
detect.) But if a copy of the pointer value has been stored in another
variable, then that copy will not be set to NULL:

p = malloc(...);
p2 = p;
...
DEALLOCATE(p);
/* p == NULL */
/* p2 is indeterminate, and probably still points to the
deallocated memory */

Apart from setting its argument to NULL and evaluating its argument
twice, there is one more difference between free() and DEALLOCATE().
The argument to free() needn't be an lvalue. For example, this is
perfectly legal:

int *p = malloc(10 * sizeof *p);
/* ... */
if (p != NULL) {
p ++;
/* ... */
free(p-1);
}

This call to free() cannot legally be replaced with a call to
DEALLOCATE. Then again, I'd probably consider it poor style anyway.
I suspect that 99+% of calls to free() pass an lvalue expression that
refers to a pointer object (or whose value is NULL).
 
C

CBFalconer

Keith said:
No, you can't. There is no implicit conversion to or from type
void**; there are only implicit conversions to and from type void*,
which is a distinct type.

You're right, and I was sloppy.
 
B

Barry Schwarz

I've been trying to write a function capable of checking if a pointer
value is set to NULL, and if it isn't, of deallocating and setting
it's value to NULL regardless of the pointer's type. I thought "void
** " should do the trick, but I kept getting the following warning
message from gcc:

warning: passing argument 1 of 'free_var' from incompatible pointer
type

which obviously could be solved by doing an explicit cast to (void **)
in the argument list when calling the fuction. That however would put
an extra burden on the programmer, so I invented the following
solution which works quite well apparently. Please give me your
opinions on this issue.

void free_var(void *vptr)
{
void **ptr = (void **) vptr;

The cast here serves no purpose. There is an implicit conversion from
vptr to any other type of object pointer.
if (ptr != NULL) {
if (*ptr != NULL) {

Here is where you can run into trouble. *ptr is by definition of type
void*. Let's assume sizeof(void*) is 8. Furthermore, assume you
actually call the function with something like
int *x = &some_int;
free_var(&x)
If sizeof(int*) is only 4, the code generated will try to evaluate an
8-byte object when the object only has four bytes. This is known as
undefined behavior.
free(*ptr);
*ptr = NULL;

These two statements don't fare any better.

You can achieve the desired result with
int *x = &some_int; /* or NULL */
x = free_var(x);

void* free_var(void *ptr){
free(ptr); /* if ptr == NULL, this is still defined */
return NULL;}

Some have suggested using a macro
#define FREE_VAR(x) (free(x), x = NULL)
which will work as long as the expression x does not have side
effects.


Remove del for email
 
B

Barry Schwarz

rocco.rossi:



void DeallocateAndNullify(void **const pp)
{
free (*pp);

*pp = 0;
}

How would I pass an int* (or its address) to this function and avoid
the undefined behavior when sizeof(void*) != sizeof(int*)?


Remove del for email
 
C

CBFalconer

Barry said:
How would I pass an int* (or its address) to this function and
avoid the undefined behavior when sizeof(void*) != sizeof(int*)?

....
int *p;
....
DeallocAndNullify(&p);
 
H

Harald van Dijk

....
int *p;
....
DeallocAndNullify(&p);

Well yes, if your code won't compile, you won't have undefined behaviour,
but I doubt that's what Barry Schwarz meant.

There is no implicit conversion from int ** to void **. There is no point
in an implicit conversion from int ** to void ** either, since the
representations of int * and void * can be completely different.
 
K

Keith Thompson

CBFalconer said:
....
int *p;
....
DeallocAndNullify(&p);
[...]

Nope. &p is of type int**; the parameter is of type void**. There is
no implicit conversion from int** to void**.

Also, your call is to DeallocAndNullify rather than
DeallocateAndNullify. (Perhaps you tried compiling your code, and the
misspelling caused the compiler not to know what the function
expects.)

[Chuck: aioe.org is free, doesn't add its own signature, and doesn't
even require signing up; you just have to set $NNTPSERVER. See their
web page for details. I've been using it myself while rr.com is under
a UDP. Please consider it.]
 
J

Joe Wright

Keith said:
CBFalconer said:
....
int *p;
....
DeallocAndNullify(&p);
[...]

Nope. &p is of type int**; the parameter is of type void**. There is
no implicit conversion from int** to void**.

But int* and void* are compatible.(?) Therefore..
DeallocAndNullify((void*)&p);
...should work.
 
S

santosh

Joe said:
Keith said:
CBFalconer said:
Barry Schwarz wrote:
rocco.rossi:
I've been trying to write a function capable of checking if a
pointer value is set to NULL, and if it isn't, of deallocating
and setting it's value to NULL regardless of the pointer's type.
I thought "void ** " should do the trick, but I kept getting the
following warning message from gcc:
void DeallocateAndNullify(void **const pp) {
free (*pp);
*pp = 0;
}
How would I pass an int* (or its address) to this function and
avoid the undefined behavior when sizeof(void*) != sizeof(int*)?
....
int *p;
....
DeallocAndNullify(&p);
[...]

Nope. &p is of type int**; the parameter is of type void**. There
is no implicit conversion from int** to void**.

But int* and void* are compatible.(?) Therefore..
DeallocAndNullify((void*)&p);
..should work.

Pass by value semantics mean that the functions becomes useless.
 
F

Flash Gordon

Joe Wright wrote, On 01/12/07 15:42:
Keith said:
CBFalconer said:
Barry Schwarz wrote:
rocco.rossi:
I've been trying to write a function capable of checking if a
pointer value is set to NULL, and if it isn't, of deallocating
and setting it's value to NULL regardless of the pointer's type.
I thought "void ** " should do the trick, but I kept getting the
following warning message from gcc:
void DeallocateAndNullify(void **const pp) {
free (*pp);
*pp = 0;
}
How would I pass an int* (or its address) to this function and
avoid the undefined behavior when sizeof(void*) != sizeof(int*)?
....
int *p;
....
DeallocAndNullify(&p);
[...]

Nope. &p is of type int**; the parameter is of type void**. There is
no implicit conversion from int** to void**.

But int* and void* are compatible.(?)

There is an implicit conversion between them which is not quite the same
thing.
Therefore..
DeallocAndNullify((void*)&p);
..should work.

No, see the comp.lang.c FAQ question 4.9 and http://c-faq.com/
I'm surprised not of the regulars have posted this reference yet.
 
C

CBFalconer

Keith said:
.... snip ...

[Chuck: aioe.org is free, doesn't add its own signature, and
doesn't even require signing up; you just have to set $NNTPSERVER.
See their web page for details. I've been using it myself while
rr.com is under a UDP. Please consider it.]

The problem is the associated nonsense. I plan to eventually
upgrade the newsreader. When I do I will be faced with that
nonsense, and one more piece won't cause much fuss. Who know,
maybe my ISP will start to function again! Meanwhile, I am VERY
lazy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,818
Latest member
Brigette36

Latest Threads

Top