473,789 Members | 2,495 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generalized function for deallocating and setting pointer to NULL

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.
Nov 29 '07 #1
27 2216
ro*********@gma il.com wrote:
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.

Nov 29 '07 #2
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 DeallocateAndNu llify(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.

--
Tomás Ó hÉilidhe
Nov 29 '07 #3
ro*********@gma il.com wrote:
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*sizeo f(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)
Nov 29 '07 #4
Charlie Gordon wrote:
"Tomás Ó hÉilidhe" <to*@lavabit.co ma écrit:
>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 DeallocateAndNu llify(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
DeallocateAndNu llify(&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.

--
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home .att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Nov 29 '07 #5
CBFalconer wrote:
Charlie Gordon wrote:
"Tom�s � h�ilidhe" <to*@lavabit.co ma �crit:
...
void DeallocateAndNu llify(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
DeallocateAndNu llify(&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.
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.

Nov 29 '07 #6
CBFalconer <cb********@yah oo.comwrites:
Charlie Gordon wrote:
>"Tomás Ó hÉilidhe" <to*@lavabit.co ma écrit:
>>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 DeallocateAndNu llify(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
DeallocateAndN ullify(&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.
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).

--
Keith Thompson (The_Other_Keit h) <ks***@mib.or g>
Looking for software development work in the San Diego area.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Nov 29 '07 #7
Keith Thompson wrote:
CBFalconer <cb********@yah oo.comwrites:
>Charlie Gordon wrote:
>>"Tomás Ó hÉilidhe" <to*@lavabit.co ma écrit:
.... snip ...
>>>
void DeallocateAndNu llify(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.
.... snip ...
>>
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.
You're right, and I was sloppy.

--
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home .att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Nov 29 '07 #8
"CBFalconer " <cb********@yah oo.coma écrit dans le message de news:
47************* *@yahoo.com...
Keith Thompson wrote:
>CBFalconer <cb********@yah oo.comwrites:
>>Charlie Gordon wrote:
"Tomás Ã" hÃ?ilidhe" <to*@lavabit.co ma écrit:
... snip ...
>>>>
void DeallocateAndNu llify(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.
... snip ...
>>>
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.

You're right, and I was sloppy.
Apology accepted.

--
Chqrlie.
Nov 29 '07 #9
On Thu, 29 Nov 2007 00:37:48 -0800 (PST), ro*********@gma il.com wrote:
>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
Dec 1 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
1745
by: christopher diggins | last post by:
I wrote a dynamic matrix class similar to the one described in TCPL 3rd Edition. Rather than define two separate iterators for const and non-const scenarios I decided to be a lazy bastard and only have one and make the data representation (a std::valarray) mutable instead. My question is, how bad is that? Am I running the risk of undefined behaviour, or is the worst case scenario simply const violation? -- Christopher Diggins...
2
11526
by: Devrobcom | last post by:
Hi I know that this is not the Lint forum, but I get some Lint warnings when setting my pointers to NULL. And the problem is I don't know howto cast a function ptr the right way. typedef int FP(char*, char*); FP *pfp; pfp = NULL; --error 64: (Error -- Type mismatch (assignment) (ptrs to void/nonvoid))
13
2365
by: dimitris67 | last post by:
How can I replace an occurence of p(a string) in an other string(s) with np(new string).. char* replace _pattern(char *s,char *p,char *np) PLEASE HELP ME!!!!!
23
7818
by: bluejack | last post by:
Ahoy... before I go off scouring particular platforms for specialized answers, I thought I would see if there is a portable C answer to this question: I want a function pointer that, when called, can be a genuine no-op. Consider: typedef int(*polymorphic_func)(int param);
5
3088
by: Jean-Guillaume Pyraksos | last post by:
I want to work with "generalized lists" as in Lisp, say : ((23 () . 2) () ((10))) ; only pointers and integers So the basic element is a node, a struct with two fields car and cdr. Each of these fields can contain either a pointer (NULL or a pointer to another node), or an int. I want to define the functions cons, car and cdr of Lisp.
78
4977
by: Josiah Manson | last post by:
I found that I was repeating the same couple of lines over and over in a function and decided to split those lines into a nested function after copying one too many minor changes all over. The only problem is that my little helper function doesn't work! It claims that a variable doesn't exist. If I move the variable declaration, it finds the variable, but can't change it. Declaring the variable global in the nested function doesn't work...
5
2257
by: FireHead | last post by:
Hello All, Its hard to explain but here it goes: char &free_malloc(char* object_copy){ Here ------------------------------------------------------------------ object_copy is parametre were the contents of the malloc object in main driver module is copied. Which would mean that if I free the object_copy it should not effect
27
3131
by: Terry | last post by:
I am getting the following warning for the below function. I understand what it means but how do I handle a null reference? Then how do I pass the resulting value? Regards Warning 1 Function 'Dec2hms' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
18
2104
by: WaterWalk | last post by:
Hello. Suppose there is an implementation of C++, in which when a class object is allocated, its member functions are also allocated in addition to its data members. So that every class object has a copy of all of its member functions. When a member function is called, it's the object's copy that When a class object is deallocated, the corresponding member functions are also deallocated. Don't consider optimization or performance, 1....
0
9506
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10193
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10136
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9979
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9016
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6761
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5548
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4089
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3695
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.