473,802 Members | 1,937 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
27 2225
Keith Thompson wrote:
>
.... 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.

--
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

Dec 1 '07 #21
CBFalconer wrote:
Keith Thompson wrote:
>CBFalconer <cb********@yah oo.comwrites:
... snip ...
>>>
....
int *p;
....
DeallocAndNulli fy(&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 DeallocAndNulli fy rather than
DeallocateAndN ullify. (Perhaps you tried compiling your code, and
the misspelling caused the compiler not to know what the function
expects.)

Consider the following test (marked as quotation for linewrap):
>[1] c:\c\junk>cat junk.c
#include <stdio.h>
#include <stdlib.h>

void release(void* *p) {
puts("Was Alive");
free(*p);
*p = NULL;
} /* release */

/* ------------------- */

int main(void) {
int *ptr;

if (ptr = malloc(sizeof *ptr)) release(&ptr);
Maybe:

if (ptr = malloc(sizeof *ptr)) release( &((void *)ptr) );

<snip>

Dec 1 '07 #22
On Sun, 02 Dec 2007 00:27:21 +0530, santosh wrote:
CBFalconer wrote:
>> if (ptr = malloc(sizeof *ptr)) release(&ptr);

Maybe:

if (ptr = malloc(sizeof *ptr)) release( &((void *)ptr) );
That won't compile. ((void *)ptr) is not an lvalue; you cannot take its
address.
Dec 1 '07 #23
Harald van D?k wrote:
On Sun, 02 Dec 2007 00:27:21 +0530, santosh wrote:
>CBFalconer wrote:
>>> if (ptr = malloc(sizeof *ptr)) release(&ptr);

Maybe:

if (ptr = malloc(sizeof *ptr)) release( &((void *)ptr) );

That won't compile. ((void *)ptr) is not an lvalue; you cannot take
its address.
Ah yes. Sorry about that.

Dec 1 '07 #24
CBFalconer wrote:
Keith Thompson wrote:
....
Consider the following test (marked as quotation for linewrap):
>[1] c:\c\junk>cat junk.c
#include <stdio.h>
#include <stdlib.h>

void release(void* *p) {
puts("Was Alive");
free(*p);
*p = NULL;
} /* release */

/* ------------------- */

int main(void) {
int *ptr;

if (ptr = malloc(sizeof *ptr)) release(&ptr);
if (ptr) puts("Alive");
else puts("Dead");

return 0;
} /* main, fcopylns */

[1] c:\c\junk>cc junk.c
junk.c: In function `main':
junk.c:15: warning: suggest parentheses around assignment used as truth value
junk.c:15: warning: passing arg 1 of `release' from incompatible pointer type

[1] c:\c\junk>a
Was Alive
Dead

Now I maintain the error is really a chimera. In release the void*
is never dereferenced, but is simply passed to free (which knows
what to do with it) and is set to NULL before exiting. The
parameter is simply a pointer to a void*.
The argument was a pointer to an int*, which means that even with a
suitable cast to silent the warning, *p==NULL has undefined behavior.
Dec 1 '07 #25
James Kuyper wrote:
Joe Wright wrote:
...
>But int* and void* are compatible.(?)

What made you think that?
Given..

int *ip;

We can do 'ip = malloc(sizeof *ip);

And now,

void *vp = ip;

...is valid. Why do you think not?

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Dec 1 '07 #26
Joe Wright wrote:
James Kuyper wrote:
>Joe Wright wrote:
...
>>But int* and void* are compatible.(?)

What made you think that?

Given..

int *ip;

We can do 'ip = malloc(sizeof *ip);

And now,

void *vp = ip;

..is valid. Why do you think not?
What you've just demonstrated is implicit conversion. Many types are
implicitly convertible to other types; section 6.3 is devoted to
describing the many ways in which this can happen. For instance, signed
char is implicitly convertible to long double _Complex. that doesn't
make them compatible.

The term "compatible types" is defined by the C standard in section
6.2.7, with cross-references to several other sections. Follow all of
those cross-references, and you won't find anything that makes "int*"
compatible with "void*".

There are only a few situations where you can access an object using an
lvalue of a one type, if the effective type of the actual object is
different. They are listed in 6.5p7, and the first one is if the lvalue
has " a type compatible with the effective type of the object". Because
int* is not compatible with void*, that case doesn't apply to this code.
Neither do any of the other cases listed in 6.5p7. Therefore, the
behavior of the program is undefined.

It might work as expected, that's one of the possibilities allowed when
the behavior of a program is undefined. On many implementations all
pointers have the same size, alignment, and representation, and on such
implementations this code could work. However, real implementations of C
have different representations for pointers to different types, and even
different sizes. This code will break on any such implementation.
Dec 2 '07 #27
CBFalconer <cb********@yah oo.comwrites:
[...]
Consider the following test (marked as quotation for linewrap):
>[1] c:\c\junk>cat junk.c
#include <stdio.h>
#include <stdlib.h>

void release(void* *p) {
puts("Was Alive");
free(*p);
*p = NULL;
} /* release */

/* ------------------- */

int main(void) {
int *ptr;

if (ptr = malloc(sizeof *ptr)) release(&ptr);
if (ptr) puts("Alive");
else puts("Dead");

return 0;
} /* main, fcopylns */

[1] c:\c\junk>cc junk.c
junk.c: In function `main':
junk.c:15: warning: suggest parentheses around assignment used as truth value
junk.c:15: warning: passing arg 1 of `release' from incompatible pointer type

[1] c:\c\junk>a
Was Alive
Dead

Now I maintain the error is really a chimera. In release the void*
is never dereferenced, but is simply passed to free (which knows
what to do with it) and is set to NULL before exiting. The
parameter is simply a pointer to a void*.
No, the error is a real error.

release() expects an argument of type void**. You give it an argument
of type int**. There is no implicit conversion from int** to void**,
so this is a constraint violation; the compiler is free to reject your
code on that basis, but it chooses instead to issue a warning and
(presumably) generate an implicit conversion anyway.

The language makes certain guarantees about the semantics of
conversions to and from void* (this is separate from the fact that
such conversions can be done implicitly). It makes no such guarantees
about conversions to or from void**, which is just another pointer
type. The conversion from int** to void** (a) is not specified by the
language, and (b) could conceivably lose information.

Now it's not likely that an implementation will actually use different
representations and/or argument passing mechanisms for void** vs.
int**, but it is entirely possible that an implementation could just
reject your code.

[...]

--
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"
Dec 2 '07 #28

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

Similar topics

6
1748
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
11528
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
2370
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
7823
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
3092
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
4981
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
2263
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
3134
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
2106
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
10538
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10305
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
10285
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,...
1
7598
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6838
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
5494
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4270
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
3792
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.