Article View: comp.std.c
Article #4500Re: Should free() take a pointer to const argument?
From: Lawrence Kirby
Date: Sun, 17 Dec 1995 17:13
Date: Sun, 17 Dec 1995 17:13
49 lines
2492 bytes
2492 bytes
In article <bcb0.smail.smayo@iii.net> smayo@iii.net "Scott Mayo" writes: >In comp.std.c, Lawrence Kirby <fred@genesis.demon.co.uk> wrote: > ><Is there any good reason why free shouldn't be declared as: > ><void free(const void *ptr); > ><in the standard? I don't believe there is any notion of altering a variable ><when it is destroyed - after all const auto variables are destroyed just like ><any other auto variable when they go out of scope. > >I like implementations of free() that scribble on the memory they free, >at least as a compile time option. I have the sense that, as const >promises no modification to the object, that there would be some >murky water there. I see no problem. Once free has destroyed an object it is at liberty to do as it pleases with the memory that the object once occupied. Back to my const auto example, a const auto variable is destroyed when it goes out of scope and in most cases the program will go on to use that memory for something else which will almost certainly involve writing to it. >I certainly would not want a compiler to assume that > > int *p; > p = malloc(sizeof(*p)); /* assume nonNULL return */ > *p = 3; > free(p); /* goodbye *p, free will piddle on you */ > use(*p); /* hey! The compiler planted use(3) here! Blast that const! */ > >could safely assume that free(p) didn't modify *p, which the const >would imply. It can't. Referring to the value of p results in undefined behaviour after the object p points to has been freed. That means any behaviour the program exhibits at all is correct. The change I propose has no bearing on that. >I'd rather have a free() that deliberately mucked *p and >then take the consequences, without the compiler hiding them. That would still be perfectly valid. -- ----------------------------------------- Lawrence Kirby | fred@genesis.demon.co.uk Wilts, England | 70734.126@compuserve.com -----------------------------------------
Technical Details
Message-ID:
<819220428snz@genesis.demon.co.uk>Path:
arc1-ca.pugleaf.net!mail2news.demon.co.uk!genesis.demon.co.ukReferences:
<818626119snz@genesis.demon.co.uk> <bcb0.smail.smayo@iii.net>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!mail2news.demon.co.uk!genesis.demon.co.uk From: Lawrence Kirby <fred@genesis.demon.co.uk> Newsgroups: comp.std.c Subject: Re: Should free() take a pointer to const argument? Date: Sun, 17 Dec 95 17:13:48 GMT Organization: none Message-ID: <819220428snz@genesis.demon.co.uk> References: <818626119snz@genesis.demon.co.uk> <bcb0.smail.smayo@iii.net> Reply-To: fred@genesis.demon.co.uk X-NNTP-Posting-Host: genesis.demon.co.uk X-Newsreader: Demon Internet Simple News v1.27