473,396 Members | 1,810 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Passing const void* to free()

Often times, I'll have some malloc()'d data in a struct that need not
change throughout the lifetime of the instance of the struct.
Therefore, the field within the struct is declared a pointer to const
[something]. But then free() complains when I pass in the pointer
because free() is declared as void free(void*). So I have to cast.

Why is it not declared as void free(const void*), which would save me
these headaches?

-Peter
Nov 14 '05 #1
16 12226
Peter Ammon <pe*********@rocketmail.com> writes:
Why is it not declared as void free(const void*), which would save me
these headaches?


Because that would make it easily possible to try to free data
that is actually defined as constant. You can always define your
own function for freeing "const" data:
void free_const(const void *p) { free((void *) p); }
--
"To get the best out of this book, I strongly recommend that you read it."
--Richard Heathfield
Nov 14 '05 #2
In <cc*********@news.apple.com> Peter Ammon <pe*********@rocketmail.com> writes:
Often times, I'll have some malloc()'d data in a struct that need not
change throughout the lifetime of the instance of the struct.
Therefore, the field within the struct is declared a pointer to const
[something]. But then free() complains when I pass in the pointer
because free() is declared as void free(void*). So I have to cast.
Welcome to the world of const poisoning. Don't use const and your
troubles are gone.
Why is it not declared as void free(const void*), which would save me
these headaches?


Because it would be semantically incorrect: this declaration promises
you that free() won't modify the data pointed to by its parameter. Or
the free() function is specified as *destroying* this data.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #3
In 'comp.lang.c', Da*****@cern.ch (Dan Pop) wrote:
Because it would be semantically incorrect: this declaration promises
you that free() won't modify the data pointed to by its parameter. Or ----------------------------------------------------------------------^
Frenchism ? Do you mean 'thus' or 'however' ? Just kidding!
the free() function is specified as *destroying* this data.


--
-ed- get my email here: http://marreduspam.com/ad672570
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-reference: http://www.dinkumware.com/manuals/reader.aspx?lib=c99
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 14 '05 #4
Dan Pop <Da*****@cern.ch> spoke thus:
Welcome to the world of const poisoning. Don't use const and your
troubles are gone.


But if things are really const, doesn't it make some sense from a
design standpoint to declare them as such?

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #5

On Wed, 7 Jul 2004, Christopher Benson-Manica wrote:

Dan Pop <Da*****@cern.ch> spoke thus:
Welcome to the world of const poisoning. Don't use const and your
troubles are gone.


But if things are really const, doesn't it make some sense from a
design standpoint to declare them as such?


Of course. But Peter Ammon was declaring something as 'const' that
patently was *not* constant --- its target was being allocated and
de-allocated (changing the contents of the pointer variable as well
as the contents of the target) during its own lifetime.

"Const poisoning" is certainly an annoying problem when it arises,
but it *usually* indicates poor design, not a flaw in the language.
Certainly in this case it's a symptom of poor design --- if you're
malloc'ing and free'ing an object, it certainly shouldn't be 'const'!

-Arthur
Nov 14 '05 #6
On 7 Jul 2004 13:09:02 GMT, Da*****@cern.ch (Dan Pop) wrote in
comp.lang.c:
In <cc*********@news.apple.com> Peter Ammon <pe*********@rocketmail.com> writes:
Often times, I'll have some malloc()'d data in a struct that need not
change throughout the lifetime of the instance of the struct.
Therefore, the field within the struct is declared a pointer to const
[something]. But then free() complains when I pass in the pointer
because free() is declared as void free(void*). So I have to cast.


Welcome to the world of const poisoning. Don't use const and your
troubles are gone.
Why is it not declared as void free(const void*), which would save me
these headaches?


Because it would be semantically incorrect: this declaration promises
you that free() won't modify the data pointed to by its parameter. Or
the free() function is specified as *destroying* this data.


No, it is defined to do no such thing.

<quote>
7.20.3.2 The free function

Synopsis

1 #include <stdlib.h>
void free(void *ptr);

Description

2 The free function causes the space pointed to by ptr to be
deallocated, that is, made available for further allocation. If ptr is
a null pointer, no action occurs. Otherwise, if the argument does not
match a pointer earlier returned by the calloc, malloc, or realloc
function, or if the space has been deallocated by a call to free or
realloc, the behavior is undefined.

Returns

3 The free function returns no value.
<end quote>

Not one single word about destroying the data, or indeed any
specification at all about what happens to the contents of the memory.
In point of fact, a strictly conforming program cannot determine
whether the contents of the memory is modified in any way or not.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #7
"Jack Klein" <ja*******@spamcop.net> wrote in message
news:pg********************************@4ax.com...
Not one single word about destroying the data, or indeed any
specification at all about what happens to the contents of the memory.
In point of fact, a strictly conforming program cannot determine
whether the contents of the memory is modified in any way or not.


The contents of the memory might not be modified, but any use of the pointer
itself becomes undefined after calling free(), so the semantics of the
argument have changed even if the value might not have. Declaring free()'s
argument as const would be nonsensical as the pointer does not have the same
semantics after the call as it did before the call, and the value of the
pointed-to memory is undefined as well.

S

--
Stephen Sprunk "Those people who think they know everything
CCIE #3723 are a great annoyance to those of us who do."
K5SSS --Isaac Asimov

Nov 14 '05 #8
In <pg********************************@4ax.com> Jack Klein <ja*******@spamcop.net> writes:
On 7 Jul 2004 13:09:02 GMT, Da*****@cern.ch (Dan Pop) wrote in
comp.lang.c:
In <cc*********@news.apple.com> Peter Ammon <pe*********@rocketmail.com> writes:
>Often times, I'll have some malloc()'d data in a struct that need not
>change throughout the lifetime of the instance of the struct.
>Therefore, the field within the struct is declared a pointer to const
>[something]. But then free() complains when I pass in the pointer
>because free() is declared as void free(void*). So I have to cast.


Welcome to the world of const poisoning. Don't use const and your
troubles are gone.
>Why is it not declared as void free(const void*), which would save me
>these headaches?


Because it would be semantically incorrect: this declaration promises
you that free() won't modify the data pointed to by its parameter. Or
the free() function is specified as *destroying* this data.


No, it is defined to do no such thing.

<quote>
7.20.3.2 The free function

Synopsis

1 #include <stdlib.h>
void free(void *ptr);

Description

2 The free function causes the space pointed to by ptr to be
deallocated, that is, made available for further allocation. If ptr is
a null pointer, no action occurs. Otherwise, if the argument does not
match a pointer earlier returned by the calloc, malloc, or realloc
function, or if the space has been deallocated by a call to free or
realloc, the behavior is undefined.

Returns

3 The free function returns no value.
<end quote>

Not one single word about destroying the data, or indeed any
specification at all about what happens to the contents of the memory.
In point of fact, a strictly conforming program cannot determine
whether the contents of the memory is modified in any way or not.


Learn to read, Jack, learn to read. If a block is deallocated, what
happens to the data it contained before deallocation? It becomes
irreversibly inaccessible, so *for all intents and purposes* it is
destroyed. No one cares whether it was actually touched by the execution
of free(), this is immaterial.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #9
In <Xn***************************@212.27.42.72> Emmanuel Delahaye <em**********@noos.fr> writes:
In 'comp.lang.c', Da*****@cern.ch (Dan Pop) wrote:
Because it would be semantically incorrect: this declaration promises
you that free() won't modify the data pointed to by its parameter. Or

----------------------------------------------------------------------^
Frenchism ? Do you mean 'thus' or 'however' ? Just kidding!

^^^^^^^^^
I am not a native French speaker, so whatever mistakes I make are very
unlikely to be caused by my French ;-)

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #10
Peter Ammon wrote:
Often times, I'll have some malloc()'d data in a struct that need not
change throughout the lifetime of the instance of the struct. Therefore,
the field within the struct is declared a pointer to const [something].
But then free() complains
Ignore the complaint.
when I pass in the pointer because free() is declared as void free(void*).
So I [must] cast.
Why is it not declared as void free(const void*),
which would save me these headaches? cat main.c #include <stdlib.h>
#define free(p) free((void*)p)

int main(int argc, char* argv[]) {
const
int* p = (int*)malloc(sizeof(int));
free(p);
return 0;
}
gcc -Wall -std=c99 -pedantic -o main main.c
./main

Nov 14 '05 #11
Jack Klein <ja*******@spamcop.net> wrote:
Da*****@cern.ch (Dan Pop) wrote:
Peter Ammon <pe*********@rocketmail.com> writes:
Why is it not declared as void free(const void*), which would save me
these headaches?


Because it would be semantically incorrect: this declaration promises
you that free() won't modify the data pointed to by its parameter. Or
the free() function is specified as *destroying* this data.


No, it is defined to do no such thing.

<quote>
7.20.3.2 The free function

Not one single word about destroying the data, or indeed any
specification at all about what happens to the contents of the memory.
In point of fact, a strictly conforming program cannot determine
whether the contents of the memory is modified in any way or not.


Before "free(p)", *p has a well-defined value. After the call to free,
*p does not have a defined value. If this does not count as
"destroying" *p, I don't know what does.
The representation of the contents of unallocated memory locations
are beyond the scope of the C standard.
Nov 14 '05 #12
Old Wolf wrote:
Jack Klein wrote:
Dan Pop wrote:
Peter Ammon writes:

Why is it not declared as void free(const void*),
which would save me these headaches?

Because it would be semantically incorrect: this declaration promises
you that free() won't modify the data pointed to by its parameter.
Or the free() function is specified as *destroying* this data.


No, it is defined to do no such thing.

<quote>
7.20.3.2 The free function

Not one single word about destroying the data, or indeed any
specification at all about what happens to the contents of the memory.
In point of fact, a strictly conforming program cannot determine
whether the contents of the memory is modified in any way or not.

Before "free(p)", *p has a well-defined value. After the call to free,
*p does not have a defined value. If this does not count as
"destroying" *p, I don't know what does.
The representation of the contents of unallocated memory locations
are beyond the scope of the C standard.


Well, *destroy* has a more specific meaning. For example:

typedef struct X {
size_t n;
char* p;
} X;

X X_create(size_t n) {
X x;
x.n = n;
x.p = (char*)malloc(n + 1);
return p;
}

void X_destroy(const X* p) {
free((void*)(p->p));
}

typedef struct Y {
X x;
double d;
} Y;

Y Y_create(size_t n, double d) {
Y y;
Y.x = X_create(n);
Y.d = d;
return y;
}

void Y_destroy(const Y* p) {
X_destroy(p);
}

Destroy means that
you call destructors for *all* of the data members
*before* you deallocate storage for the object itself.

Y* p = (Y*)malloc(sizeof(Y));
*p = Y_create(13, 33.0);
free(p); // error: memory leak!
Nov 14 '05 #13
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote:
Peter Ammon wrote:
Often times, I'll have some malloc()'d data in a struct that need not
change throughout the lifetime of the instance of the struct. Therefore,
the field within the struct is declared a pointer to const [something].
But then free() complains


Ignore the complaint.


Rarely a good idea. In this case, it's relatively harmless, but it's
always better to make sure you don't need to ignore compiler warnings,
if only because if you get into the habit, you will one day ignore a
warning that does mean something serious.
when I pass in the pointer because free() is declared as void free(void*).
So I [must] cast.
Why is it not declared as void free(const void*),
which would save me these headaches?

> cat main.c

#include <stdlib.h>
#define free(p) free((void*)p)


Congratulations, you've just thrown out all type safety C could provide
you when using that function.

free(104977);

anyone?

Richard
Nov 14 '05 #14
In <cc**********@nntp1.jpl.nasa.gov> "E. Robert Tisdale" <E.**************@jpl.nasa.gov> writes:
Peter Ammon wrote:
Often times, I'll have some malloc()'d data in a struct that need not
change throughout the lifetime of the instance of the struct. Therefore,
the field within the struct is declared a pointer to const [something].
But then free() complains
Ignore the complaint.


I wouldn't have expected anything less from Trollsdale.
when I pass in the pointer because free() is declared as void free(void*).
So I [must] cast.
Why is it not declared as void free(const void*),
which would save me these headaches?

> cat main.c

#include <stdlib.h>
#define free(p) free((void*)p)


- Each identifier with file scope listed in any of the following
subclauses (including the future library directions) is
reserved for use as a macro name and as an identifier with
file scope in the same name space if any of its associated
headers is included.

2 No other identifiers are reserved. If the program declares or
defines an identifier in a context in which it is reserved (other
than as allowed by 7.1.4), or defines a reserved identifier as
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
a macro name, the behavior is undefined.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #15
Dan Pop wrote:
In <cc*********@news.apple.com> Peter Ammon <pe*********@rocketmail.com> writes:

Often times, I'll have some malloc()'d data in a struct that need not
change throughout the lifetime of the instance of the struct.
Therefore, the field within the struct is declared a pointer to const
[something]. But then free() complains when I pass in the pointer
because free() is declared as void free(void*). So I have to cast.

Welcome to the world of const poisoning. Don't use const and your
troubles are gone.


I find that casting everything to void* gets rid of a lot of troubles too.

Why is it not declared as void free(const void*), which would save me
these headaches?

Because it would be semantically incorrect: this declaration promises
you that free() won't modify the data pointed to by its parameter. Or
the free() function is specified as *destroying* this data.


But free() isn't modifying the data pointed to by its parameter: it's
modifying the semantics of the value of the parameter itself, which is a
much stronger and almost totally unique side effect, very different from
modifying the data pointed to.

int* foo = some_allocated_int_somewhere();
*foo = 0;
some_function(foo);
*foo = 1;

No matter whether some_function() is declared to take an int* or a const
int*, that code is always completely legal...unless some_function()
invokes free() somewhere. Thus free() is a very special case, and "it's
not const, so it might modify what its parameter points to" doesn't
capture what's going on at all.

It's interesting to note that a similar situation arises at the other
point where C destroys memory, namely, when an automatic variable goes
out of scope:

const char* function(void) {
const char buff[] = "I am const";
return buff;
}

buff is defined to be const, but all the constness in the world can't
save it from being destroyed. So that's why IMO const isn't appropriate
for expressing "data that cannot be destroyed."

Since the only restriction on free() is that the pointer value was
returned by the alloc() family of functions (or is NULL), I see no
reason to disallow const pointers to be passed in, for the same reason
we don't disallow const pointers in functions such as strcmp().

-Peter
Nov 14 '05 #16
Peter Ammon wrote:
Often times, I'll have some malloc()'d data in a struct that need not
change throughout the lifetime of the instance of the struct. Therefore,
the field within the struct is declared a pointer to const [something].
But then free() complains when I pass in the pointer
because free() is declared as void free(void*). So I [must] cast.

Why is it not declared as void free(const void*),
which would save me these headaches?
I don't know. I don't think that there is a good reason.
The C++ 'delete' operator deletes constant ans well as variable memory:
cat main.cc int main(int argc, char* argv[]) {
const int* p = new int[16];
delete [] p;
return 0;
}

You can redefine free(void*):
cat main.c

#include <stdlib.h>

inline static
void freeConst(const void* p) {
free((void*)p);
}

#define free(p) freeConst(p)

int main(int argc, char* argv[]) {
const void* p = malloc(16);
free(p);
return EXIT_SUCCESS;
}

to provide the same behavior.
Nov 14 '05 #17

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

Similar topics

8
by: Alex Vinokur | last post by:
Various forms of argument passing ================================= C/C++ Performance Tests ======================= Using C/C++ Program Perfometer...
17
by: BlindHorse | last post by:
Help!!! I need someone to tell me why I am getting the err msg error C2440: '=' : cannot convert from 'char *' to 'char' //==================== #include <iostream>
9
by: Colin Doig | last post by:
Hi, I need to pass an array of strings to a function, but I can't get it to work. This is what I wrote : #include <stdio.h> void a_function(char *blah) { printf("%s %s %s", blah, blah,...
3
by: Goh, Yong Kwang | last post by:
I'm trying to create a function that given a string, tokenize it and put into a dynamically-sized array of char* which is in turn also dynamically allocated based on the string token length. I...
14
by: Enrico `Trippo' Porreca | last post by:
Given: typedef struct Node Node; struct Node { void *obj; Node *next; }; typedef struct Stack Stack; struct Stack {
1
by: george doubleu | last post by:
hi, i'm using "gcc version 3.3.3 (Debian)" to compile the program pasted below. I get the two warnings you can see in the remarks. The second warning is perfectly OK for me, but the first one I...
11
by: MackS | last post by:
I've come across the following difficulty, related to questions 6.12, 6.13 and 6.18 in the FAQ, which I am unable to overcome: void fun(char **array_of_strings, int num_elements); int...
17
by: Charles Sullivan | last post by:
The library function 'qsort' is declared thus: void qsort(void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *)); If in my code I write: int cmp_fcn(...); int...
0
by: wellingj | last post by:
A little back ground on what I'm trying to do: I'm making a generic weighted graph class (vertexes and edges althought I don't call them that) to implement some pathfinding algorithms like A* and D*....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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...
0
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...
0
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,...

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.