By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,301 Members | 1,752 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,301 IT Pros & Developers. It's quick & easy.

free()

P: n/a
Hi group,

I have a question to ask you all. I have allocated some chunk of
memory using ptr=(int*)malloc(). now I am trying to free that memory
using free((void*)ptr). My question is does free() make ptr NULL? If
not how do we know whether ptr memory has been freed already and we
should not try to free the same memory twice. Man pages does not tell
anything about this behavoiur.

Thanks,

Feb 10 '07 #1
Share this Question
Share on Google+
76 Replies


P: n/a
dbansal wrote:
Hi group,

I have a question to ask you all. I have allocated some chunk of
memory using ptr=(int*)malloc().
I very much doubt it. Have a look a the the scores of messages over the
past couple of days regarding the correct use of malloc.
now I am trying to free that memory
using free((void*)ptr).
Why on Earth would you cast the pointer?
My question is does free() make ptr NULL?
No, how could it?
If not how do we know whether ptr memory has been freed already and we
should not try to free the same memory twice. Man pages does not tell
anything about this behavoiur.
It's undefined behaviour. You have to manage your own pointers.

--
Ian Collins.
Feb 10 '07 #2

P: n/a
dbansal said:
Hi group,

I have a question to ask you all. I have allocated some chunk of
memory using ptr=(int*)malloc().
Drop the pointless obfuscatory cast.
now I am trying to free that memory
using free((void*)ptr).
And that one.
My question is does free() make ptr NULL?
No.
If
not how do we know whether ptr memory has been freed already
free(ptr);
ptr = NULL;

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 10 '07 #3

P: n/a
On Feb 10, 7:45 am, "dbansal" <bansal...@gmail.comwrote:
Hi group,

I have a question to ask you all. I have allocated some chunk of
memory using ptr=(int*)malloc(). now I am trying to free that memory
using free((void*)ptr). My question is does free() make ptr NULL?
You have no clue what you're talking about. Think about it for one
tiny second... free is a function that's passed ptr by value, so how
on earth do you imagine it could set it to NULL?
If
not how do we know whether ptr memory has been freed already and we
should not try to free the same memory twice. Man pages does not tell
anything about this behavoiur.
Maybe the writers of the man pages assumed their readers would have
some small amount of intelligence and/or have invested some time in
learning the C language before trying to program in it?

--
"One of the great strengths of C from its earliest days has been its
ability to manipulate sequences of characters."
- P. J. Plauger

Feb 10 '07 #4

P: n/a
dbansal wrote:
Hi group,

I have a question to ask you all. I have allocated some chunk of
memory using ptr=(int*)malloc().
The cast is not needed, indeed even counterproductive, in C.
now I am trying to free that memory
using free((void*)ptr).
Same as above.
My question is does free() make ptr NULL?
No.
If not how do we know whether ptr memory has been freed already and we
should not try to free the same memory twice. Man pages does not tell
anything about this behavoiur.
As long as you pass a value previously obtained from malloc() calloc()
or realloc(), free() will succeed. If the argument is a null pointer
value, free() does nothing.

There's no mechanism in C to tell you if a pointer value points to
validly addressable memory or not. You'll have to keep track of such
things yourself. One safe practise is to immediately set a pointer to
NULL after calling free() on it. Passing a null pointer to free() is
harmless.

Feb 10 '07 #5

P: n/a
In article <53**************@mid.individual.net>,
Ian Collins <ia******@hotmail.comwrote:
>dbansal wrote:
>Hi group,

I have a question to ask you all. I have allocated some chunk of
memory using ptr=(int*)malloc().

I very much doubt it.
How can you say this? I don't doubt it at all (that he did what he says
he did).

Anyway, sounds like the OP should add this to his toolkit:

void myfree(void **ptr) {
free(*ptr);
*ptr = NULL;
}

Feb 10 '07 #6

P: n/a
Kenny McCormack said:
In article <53**************@mid.individual.net>,
Ian Collins <ia******@hotmail.comwrote:
>>dbansal wrote:
>>Hi group,

I have a question to ask you all. I have allocated some chunk of
memory using ptr=(int*)malloc().

I very much doubt it.

How can you say this?
Because it won't compile.
I don't doubt it at all (that he did what he says he did).
Figures.
>
Anyway, sounds like the OP should add this to his toolkit:

void myfree(void **ptr) {
free(*ptr);
*ptr = NULL;
}
The problem with that is that you can't pass anything to it, except the
address of a void pointer. void ** does not have the same guarantees as
void *.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 10 '07 #7

P: n/a
Kenny McCormack wrote:
In article <53**************@mid.individual.net>,
Ian Collins <ia******@hotmail.comwrote:
dbansal wrote:
Hi group,

I have a question to ask you all. I have allocated some chunk of
memory using ptr=(int*)malloc().
I very much doubt it.

How can you say this? I don't doubt it at all (that he did what he says
he did).
I doubt that he managed to call malloc without passing it any
argument.
Anyway, sounds like the OP should add this to his toolkit:

void myfree(void **ptr) {
free(*ptr);
*ptr = NULL;
}
ptr is probably declared as a pointer to int (judging from the cast),
so myfree(&ptr) won't work. If you want to always set a freed pointer
of any type to NULL, you'll need either compiler-specific extensions,
or you'll need a macro.
#define myfree(p) (free(p), p = NULL)
Of course, the usual problems apply, but I'm sure you know them
already.

Feb 10 '07 #8

P: n/a
On 9 Feb 2007 23:45:46 -0800, in comp.lang.c , "dbansal"
<ba*******@gmail.comwrote:
>Hi group,

I have a question to ask you all. I have allocated some chunk of
memory using ptr=(int*)malloc(). now I am trying to free that memory
using free((void*)ptr).
Neither of those casts is necessary, and if you're writing C, it is
strongly recommended by most experts that you don't insert them.
>My question is does free() make ptr NULL?
No.
>If not how do we know whether ptr memory has been freed already
free()ing a null pointer is safe.

7.20.3.2 The free function
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.

--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Feb 10 '07 #9

P: n/a
dbansal wrote:
Hi group,

I have a question to ask you all. I have allocated some chunk of
memory using ptr=(int*)malloc(). now I am trying to free that memory
^^^^^^^^^^^^^^^^^^
The cast to (int *) is unnecessary and poor style.
malloc requires an argument; not supplying one is an error.
No matter what kind of argument ptr points to (but it should be a pointer)
ptr = malloc(sizeof *ptr);
will work, but you should check to see that the result is not NULL.
using free((void*)ptr).
The cast to (void *) is unnecessary and poor style.
My question is does free() make ptr NULL?
No, but you haven't learned enough C to be bothered with such questions yet.
If
not how do we know whether ptr memory has been freed already
You hire a competent programmer.
Feb 10 '07 #10

P: n/a
"santosh" <sa*********@gmail.comwrites:
[...]
There's no mechanism in C to tell you if a pointer value points to
validly addressable memory or not. You'll have to keep track of such
things yourself. One safe practise is to immediately set a pointer to
NULL after calling free() on it. Passing a null pointer to free() is
harmless.
That's only relatively safe; if you've made copies of the pointer
before free()ing it, those copies become indeterminate.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 11 '07 #11

P: n/a
On Feb 10, 3:45 pm, "dbansal" <bansal...@gmail.comwrote:
Hi group,

I have a question to ask you all. I have allocated some chunk of
memory using ptr=(int*)malloc(). now I am trying to free that memory
using free((void*)ptr). My question is does free() make ptr NULL? If
not how do we know whether ptr memory has been freed already and we
should not try to free the same memory twice. Man pages does not tell
anything about this behavoiur.

Thanks,
Sure not. free() marks the allocated memory chunk to 'not in use'
state, that means your program has lost control to the chunk, and this
chunk can be TAKEN BY SOME OTHER CODE. And the value of your pa
remains unchanged, THIS IS VERY DANGEROUS, because you may try to read/
write the memory space which not belongs to you, this behavior will
cause an security alert on most operating systems.

Feb 12 '07 #12

P: n/a
On Feb 10, 2:13 pm, "santosh" <santosh....@gmail.comwrote:
things yourself. One safe practise is to immediately set a pointer to
NULL after calling free() on it. Passing a null pointer to free() is
harmless.
this is a very bad idea.

instead of having your code crash like hell in the
first phases of debugging, which will allow you
to fix the thing quick & properly, you will happily
call free() many times on the same pointer, and
build crap around that broken logic, and then
call for a garbage collector :)

Feb 12 '07 #13

P: n/a
Racaille said:
On Feb 10, 2:13 pm, "santosh" <santosh....@gmail.comwrote:
>things yourself. One safe practise is to immediately set a pointer to
NULL after calling free() on it. Passing a null pointer to free() is
harmless.

this is a very bad idea.
Setting pointers to NULL after a free() is a very good idea indeed.
Having indeterminate values around the place is a bad idea. I agree
that passing a null pointer to free() indicates a design flaw.
instead of having your code crash like hell in the
first phases of debugging, which will allow you
to fix the thing quick & properly,
Chapter and verse, please. Where does the Standard guarantee that your
code will crash like hell when you pass a pointer to free() a second
time?
you will happily call free() many times on the same pointer, and
build crap around that broken logic, and then call for a garbage
collector :)
Will I really? How long does that process take, from the time I first
decide not to let indeterminate values plague my debugging to the time
I first call for a garbage collector?

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 13 '07 #14

P: n/a
On Feb 13, 9:16 am, Richard Heathfield <r...@see.sig.invalidwrote:
Setting pointers to NULL after a free() is a very good idea indeed.
Having indeterminate values around the place is a bad idea. I agree
that passing a null pointer to free() indicates a design flaw.
What's your point ?
santosh was suggesting to set the pointer to NULL in order to be able
to 'safely' call free() again on it - first you say that this is a
'very
good idea', then that it indicates a 'design flaw'.

As of indeterminate values, you have them floating around all the time
-
otherwise you would be able (like God) to resolve everything at
compile time.

That is pure sophistry - please try to be honest and don't abuse your
better
control of English to push that crap.
Chapter and verse, please. Where does the Standard guarantee that your
code will crash like hell when you pass a pointer to free() a second
time?
Better you tell me how to (chapter/verse-) portably 0xdeadbeef a
pointer.

How to portably generate an 'invalid' pointer. NULL/0 doesn't qualify,
since it's common practice for interfaces to either ignore NULL
pointers
(see free()) or to interpret them as 'default value'.
you will happily call free() many times on the same pointer, and
build crap around that broken logic, and then call for a garbage
collector :)

Will I really? How long does that process take, from the time I first
decide not to let indeterminate values plague my debugging to the time
I first call for a garbage collector?
I don't know - how much does it take from the first time I decided not
to
let the dihydrogen monoxide plague my life to the time I will be
generation-scavangered ?

Feb 13 '07 #15

P: n/a
Racaille wrote:
Better you tell me how to (chapter/verse-) portably 0xdeadbeef a
pointer.

How to portably generate an 'invalid' pointer. NULL/0 doesn't qualify,
since it's common practice for interfaces to either ignore NULL
pointers
(see free()) or to interpret them as 'default value'.
I'm sure I'm misunderstanding what you're asking for, but the
sequence:

void *spoo = malloc(1);
free( spoo );

makes `spoo` an invalid pointer.

Of course, /because/ it's invalid, you can't use it for anything,
so I'm not sure what you wanted it for -- see first sentence ...

--
Chris "electric hedgehog" Dollin
"I'm still here and I'm holding the answers" - Karnataka, /Love and Affection/

Feb 13 '07 #16

P: n/a
Racaille said:
On Feb 13, 9:16 am, Richard Heathfield <r...@see.sig.invalidwrote:
>Setting pointers to NULL after a free() is a very good idea indeed.
Having indeterminate values around the place is a bad idea. I agree
that passing a null pointer to free() indicates a design flaw.

What's your point ?
I have two - firstly that the issue of setting indeterminate pointer
values to NULL is actually a good idea (so I disagree with you there),
and secondly that passing a null pointer to free() indicates a badly
written program (so I agree with you there). Did I not make this clear?
santosh was suggesting to set the pointer to NULL in order to be able
to 'safely' call free() again on it - first you say that this is a
'very
good idea', then that it indicates a 'design flaw'.
Two separate issues.
As of indeterminate values, you have them floating around all the time
No, I don't.
-
otherwise you would be able (like God) to resolve everything at
compile time.
I don't see why that follows. Please explain further.
That is pure sophistry - please try to be honest and don't abuse your
better control of English to push that crap.
It is not sophistry, I am being honest, I don't see what my use of
English has to do with this, and I'm not pushing anything - so I'm
afraid you're 100% wrong there.
>Chapter and verse, please. Where does the Standard guarantee that
your code will crash like hell when you pass a pointer to free() a
second time?

Better you tell me how to (chapter/verse-) portably 0xdeadbeef a
pointer.
If you mean "how can I set a pointer to a value which I can reliably
interrogate to ensure that I can know that dereferencing the pointer
would be invalid?", the answer is simple: ptr = NULL;
How to portably generate an 'invalid' pointer.
ptr = NULL;
NULL/0 doesn't qualify,
Yes, it does.
since it's common practice for interfaces to either ignore NULL
pointers
That's their problem (or opportunity, or feature, or whatever you like
to call it), not mine.
(see free()) or to interpret them as 'default value'.
See above.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 13 '07 #17

P: n/a

Racaille wrote:
On Feb 10, 2:13 pm, "santosh" <santosh....@gmail.comwrote:
things yourself. One safe practise is to immediately set a pointer to
NULL after calling free() on it. Passing a null pointer to free() is
harmless.

this is a very bad idea.

instead of having your code crash like hell in the
first phases of debugging, which will allow you
to fix the thing quick & properly, you will happily
call free() many times on the same pointer, and
build crap around that broken logic, and then
call for a garbage collector :)
I argue that attempting to ensure that pointers are either null or
have legally deferencible values is better. A null pointer is by
definition an unusable pointer. A pointer with an indeterminate value,
on the other hand, may or may not exhibit observable error, when
misused. I prefer to take the more deterministic route.

Feb 13 '07 #18

P: n/a
"santosh" <sa*********@gmail.comwrote:
Racaille wrote:
On Feb 10, 2:13 pm, "santosh" <santosh....@gmail.comwrote:
things yourself. One safe practise is to immediately set a pointer to
NULL after calling free() on it. Passing a null pointer to free() is
harmless.
this is a very bad idea.

instead of having your code crash like hell in the first phases of debugging,
which will allow you to fix the thing quick & properly, you will happily
call free() many times on the same pointer, and build crap around that broken
logic, and then call for a garbage collector :)

I argue that attempting to ensure that pointers are either null or
have legally deferencible values is better.
The problem with that is "attempting". You will, sooner or later, fail
in your attempt. And then, because you believe that all your pointers
are either null or valid, you will not be able to find the bug until
someone else points it out to you. Making sure that you know which of
your pointers are still in use _is_ possible, and does not have this
problem.

Richard
Feb 13 '07 #19

P: n/a
Richard Bos wrote:
"santosh" <sa*********@gmail.comwrote:
>>Racaille wrote:
>>>On Feb 10, 2:13 pm, "santosh" <santosh....@gmail.comwrote:

things yourself. One safe practise is to immediately set a pointer to
NULL after calling free() on it. Passing a null pointer to free() is
harmless.

this is a very bad idea.

instead of having your code crash like hell in the first phases of debugging,
which will allow you to fix the thing quick & properly, you will happily
call free() many times on the same pointer, and build crap around that broken
logic, and then call for a garbage collector :)

I argue that attempting to ensure that pointers are either null or
have legally deferencible values is better.

The problem with that is "attempting". You will, sooner or later, fail
in your attempt. And then, because you believe that all your pointers
are either null or valid, you will not be able to find the bug until
someone else points it out to you. Making sure that you know which of
your pointers are still in use _is_ possible, and does not have this
problem.
Can you cite an example where setting a pointer to NULL could mask a
bug? The way I see it is there are three things you can do with a
pointer, test it, dereference it and free it. Once set to NULL, the
first to will fail and the third is harmless.

--
Ian Collins.
Feb 13 '07 #20

P: n/a
Ian Collins <ia******@hotmail.comwrote:
Richard Bos wrote:
The problem with that is "attempting". You will, sooner or later, fail
in your attempt. And then, because you believe that all your pointers
are either null or valid, you will not be able to find the bug until
Can you cite an example where setting a pointer to NULL could mask a
bug? The way I see it is there are three things you can do with a
pointer, test it, dereference it and free it. Once set to NULL, the
first to will fail and the third is harmless.
You missed Richard's point. The problem lies not in setting the
pointer to NULL, but in *believing* one has when in fact one has not.

--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gmail.com | don't, I need to know. Flames welcome.
Feb 13 '07 #21

P: n/a
Christopher Benson-Manica said:
Ian Collins <ia******@hotmail.comwrote:
>Richard Bos wrote:
The problem with that is "attempting". You will, sooner or later,
fail in your attempt. And then, because you believe that all your
pointers are either null or valid, you will not be able to find the
bug until
>Can you cite an example where setting a pointer to NULL could mask a
bug? The way I see it is there are three things you can do with a
pointer, test it, dereference it and free it. Once set to NULL, the
first to will fail and the third is harmless.

You missed Richard's point. The problem lies not in setting the
pointer to NULL, but in *believing* one has when in fact one has not.
Lots of problems can arise from believing one has done something when in
fact one has not. That doesn't mean that the something is a bad thing
to do.

Short of writing an entire pointer management subsystem, there isn't
much you can do with a pointer to check it for validity, but you *can*
test it against NULL. If you know it's NULL, you know it's invalid. If
it isn't NULL, you can't be sure either way. So setting it to NULL when
it would otherwise be indeterminate is a Good Thing, because it
increases the amount of information available to you at a trivial cost.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 13 '07 #22

P: n/a
santosh wrote:
>
.... snip ...
>
I argue that attempting to ensure that pointers are either null or
have legally deferencible values is better. A null pointer is by
definition an unusable pointer. A pointer with an indeterminate
value, on the other hand, may or may not exhibit observable error,
when misused. I prefer to take the more deterministic route.
The point is that the attempt will involve some sort of operation
on the pointer, comparison, masking, whatever. For an invalid
pointer that operation itself will involve undefined behaviour.
Remember, we are talking portable standard C, not system dependent
kluges. In fact:

p = malloc(10);
free(p);
if (p) .... /* involves undefined behaviour */

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>

"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
Feb 14 '07 #23

P: n/a
CBFalconer said:
santosh wrote:
>>
... snip ...
>>
I argue that attempting to ensure that pointers are either null or
have legally deferencible values is better. A null pointer is by
definition an unusable pointer. A pointer with an indeterminate
value, on the other hand, may or may not exhibit observable error,
when misused. I prefer to take the more deterministic route.

The point is that the attempt will involve some sort of operation
on the pointer, comparison, masking, whatever. For an invalid
pointer that operation itself will involve undefined behaviour.
Remember, we are talking portable standard C, not system dependent
kluges. In fact:

p = malloc(10);
free(p);
if (p) .... /* involves undefined behaviour */
Yes, but santosh knows that already. He is saying he prefers:

p = malloc(10);
if(p != NULL)
{
use(p);
free(p);
p = NULL;
}
/* [1] */
if(p != NULL) /* doesn't involve undefined behaviour */

Of course, this check is rather pointless as it stands in this trivial
example, but if you add code at [1] which may change p's value, it
becomes less silly.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 14 '07 #24

P: n/a
On Feb 13, 3:58 pm, Richard Heathfield <r...@see.sig.invalidwrote:
Racaille said:
On Feb 13, 9:16 am, Richard Heathfield <r...@see.sig.invalidwrote:
Setting pointers to NULL after a free() is a very good idea indeed.
Having indeterminate values around the place is a bad idea. I agree
that passing a null pointer to free() indicates a design flaw.
santosh was suggesting to set the pointer to NULL in order to be able
to 'safely' call free() again on it - first you say that this is a
'very
good idea', then that it indicates a 'design flaw'.
That is pure sophistry - please try to be honest and don't abuse your
better control of English to push that crap.

It is not sophistry, I am being honest, I don't see what my use of
English has to do with this, and I'm not pushing anything - so I'm
afraid you're 100% wrong there.
You're pushing another 'rule of thumb' (every time set a pointer to
NULL
after free()ing it, just do it mechanically, even if it is NOT
required by
the logic of the program).

That is horrible - not only because is yet another 'simple rule'/cargo
cult
thing, but also because it's actively obfuscating serious problems,
like
freeing the same pointer multiple times.

Feel free to be happy about people taking your advice - They won't ask
you to
debug their programs, after all ;)

Feb 14 '07 #25

P: n/a
Racaille wrote:
>
That is horrible - not only because is yet another 'simple rule'/cargo
cult
thing, but also because it's actively obfuscating serious problems,
like
freeing the same pointer multiple times.
If a pointer is null, you can free it as often as you like. Try to
dereference it and you'll soon know what's wrong. Dereferencing or
freeing an invalid pointer has undefined and indeterminate results.

--
Ian Collins.
Feb 14 '07 #26

P: n/a
Richard Heathfield wrote:
CBFalconer said:
>santosh wrote:
>>>
... snip ...
>>>
I argue that attempting to ensure that pointers are either null or
have legally deferencible values is better. A null pointer is by
definition an unusable pointer. A pointer with an indeterminate
value, on the other hand, may or may not exhibit observable error,
when misused. I prefer to take the more deterministic route.

The point is that the attempt will involve some sort of operation
on the pointer, comparison, masking, whatever. For an invalid
pointer that operation itself will involve undefined behaviour.
Remember, we are talking portable standard C, not system dependent
kluges. In fact:

p = malloc(10);
free(p);
if (p) .... /* involves undefined behaviour */

Yes, but santosh knows that already. He is saying he prefers:
....

What santosh knows is immaterial here. What he said is material.
The idea is to clear up misconceptions that may be drawn by nubile
nymphlike newbies.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>

"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
Feb 14 '07 #27

P: n/a
Racaille said:
On Feb 13, 3:58 pm, Richard Heathfield <r...@see.sig.invalidwrote:
>Racaille said:
<snip>
That is pure sophistry - please try to be honest and don't abuse
your better control of English to push that crap.

It is not sophistry, I am being honest, I don't see what my use of
English has to do with this, and I'm not pushing anything - so I'm
afraid you're 100% wrong there.

You're pushing another 'rule of thumb' (every time set a pointer to
NULL after free()ing it, just do it mechanically, even if it is NOT
required by the logic of the program).
No, I'm not pushing it at all. I'm expressing my opinion that it's a
very good idea, but I have certainly not claimed that not doing it is a
very bad idea. People make up their own minds.
That is horrible - not only because is yet another 'simple rule'/cargo
cult thing, but also because it's actively obfuscating serious
problems, like freeing the same pointer multiple times.
I don't understand why anyone would want to free the same pointer
multiple times, so I don't see why it's an issue.

Feel free to be happy about people taking your advice
I was offering my opinion, not my advice.
- They won't ask you to debug their programs, after all ;)
You clearly haven't been here very long. People *do* ask me to debug
their programs. I find that task much easier when the bugs stand still
instead of hopping around all over memory.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 14 '07 #28

P: n/a
Ian Collins said:
Racaille wrote:
>>
That is horrible - not only because is yet another 'simple
rule'/cargo cult
thing, but also because it's actively obfuscating serious problems,
like
freeing the same pointer multiple times.
If a pointer is null, you can free it as often as you like.
Zero, for preference. Why would you bother to pass NULL to free()?
Try to dereference it and you'll soon know what's wrong.
Quite so.
Dereferencing or
freeing an invalid pointer has undefined and indeterminate results.
....which is why indeterminate pointers are a bad idea - you can't tell
whether or not they are invalid.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 14 '07 #29

P: n/a
CBFalconer said:
Richard Heathfield wrote:
<snip>
>Yes, but santosh knows that already. He is saying he prefers:
...

What santosh knows is immaterial here. What he said is material.
It is from what he said that I deduced what he knows.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 14 '07 #30

P: n/a
Richard Heathfield wrote:
Ian Collins said:
>Racaille wrote:
>>>
That is horrible - not only because is yet another 'simple
rule'/cargo cult
thing, but also because it's actively obfuscating serious problems,
like
freeing the same pointer multiple times.
If a pointer is null, you can free it as often as you like.

Zero, for preference. Why would you bother to pass NULL to free()?
You wouldn't (except perhaps for testing purposes).

But you might very well pass a null pointer to `free`.

struct stuff { int n; Other *other; };

struct stuff* newStuff() { ... result->other = 0; ... }

... code possibly setting `other` to a non-null pointer ...

finally

void freeStuff( struct stuff *stuff )
{
free( stuff->other );
free( stuff );
}

Of course you might argue that you could, maybe should, write

if (stuff) free( stuff );

but (a) why should you, since `free` is defined to work on
null pointers, and (b) if you write the sequence `if (x) free(x);`
several times, DRY says "make that a function!". At which point
you realise you needn't have bothered, because Mr Standard
was there first.

--
Chris "electric hedgehog" Dollin
"The path to the web becomes deeper and wider" - October Project

Feb 14 '07 #31

P: n/a
On Feb 10, 1:22 pm, Richard Heathfield <r...@see.sig.invalidwrote:
dbansal said:
Hi group,
I have a question to ask you all. I have allocated some chunk of
memory using ptr=(int*)malloc().

Drop the pointless obfuscatory cast.
now I am trying to free that memory
using free((void*)ptr).

And that one.
My question is does free() make ptr NULL?

No.
If
not how do we know whether ptr memory has been freed already

free(ptr);
ptr = NULL;
This is Interesting..! I am just putting small code to check some
stuff.
/* Start test1.c */

#include<stdio.h>
#include<string.h>
#include<malloc.h>
int main()
{

char *p;
char*q;

p=(char *) malloc(100);

/* I should do memset but ... */

strcpy(p,"raxit sheth");

q=p;

printf("\nP=%p : %s",p,p);
printf("\nQ=%p :%s",q,q);
fflush(stdout);
free(p);
/* p=NULL; */

printf("\n AFTER FREE ");
printf("\nP=%p : %s",p,p);
printf("\nQ=%p : %s",q,q);
return 0;

}
/* end */

output on linux box (valgrind shows double free error)
$gcc -g3 -Wall test1.c -o test1
$./test1
P=0x8049800 : raxit sheth
Q=0x8049800 :raxit sheth
AFTER FREE
P=0x8049800 : raxit sheth
Q=0x8049800 : raxit sheth
Now Uncommented p=NULL in above code. Output is

P=0x8049810 : raxit sheth
Q=0x8049810 :raxit sheth
AFTER FREE
P=(nil) : (null)
Q=0x8049810 : raxit sheth <----important
I think (correct me if I am wrong, I am learning here.)

1.this technique is useful in some case but not in all where pointer
assignment is doing like this way. q is pointing to same memory
location as of p before free, and doing p=NULL is not helpful for q.
2. normally sequence,

p=NULL;
malloc,
memset,bzero or equivalent
use of memory
free
May be p=NULL.

can be

p=NULL;
malloc,
memset,bzero or equivalent
use of memory
memset,<---Some practical limitation. I may not be knowing what
size to free and howmany bytes to memset.
free
(p=NULL ?)
any opinion on this ? Adv/Disadv/limitation/ ?
--Raxit Sheth
Feb 14 '07 #32

P: n/a
ra************@yahoo.co.in said:

<snip>
/* Start test1.c */

#include<stdio.h>
#include<string.h>
#include<malloc.h>
No such header in C. For malloc()'s prototype, use this instead:

#include <stdlib.h>
int main()
{

char *p;
char*q;

p=(char *) malloc(100);
The cast is unnecessary, as I have already explained to you.
>
/* I should do memset but ... */
No, you should check that the allocation succeeded before relying on it.

if(p != NULL)
{
>
strcpy(p,"raxit sheth");
That's fine.
>
q=p;
That's legal.
printf("\nP=%p : %s",p,p);
printf("P=%p : %s\n", (void *)p, p);
printf("\nQ=%p :%s",q,q);
printf("Q=%p : %s\n", (void *)q, q);
fflush(stdout);
free(p);
That's fine. The value that p and q shared is now indeterminate, so you
won't be able to evaluate p or q again until they've been given new
values.
/* p=NULL; */
Why comment that out?
printf("\n AFTER FREE ");
printf("\nP=%p : %s",p,p);
That's illegal, because you are using the value of an indeterminate
pointer.
printf("\nQ=%p : %s",q,q);
Likewise.
return 0;

}
/* end */

output on linux box
....is irrelevant, because you broke the rules of C, so any output you
get is not bound by those rules.
Now Uncommented p=NULL in above code.
It doesn't matter. The program remains broken because you are evaluating
p and q.
I think (correct me if I am wrong, I am learning here.)

1.this technique is useful in some case but not in all where pointer
assignment is doing like this way. q is pointing to same memory
location as of p before free, and doing p=NULL is not helpful for q.
If you give q a value which later becomes indeterminate, it's your job
to make sure you don't evaluate q.
any opinion on this ? Adv/Disadv/limitation/ ?
I recommend that you study the rules of C carefully before you decide on
a programming strategy for memory management.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 14 '07 #33

P: n/a
On Feb 14, 2:33 pm, Richard Heathfield <r...@see.sig.invalidwrote:
raxitsheth2...@yahoo.co.in said:

<snip>
/* Start test1.c */
#include<stdio.h>
#include<string.h>
#include<malloc.h>

No such header in C. For malloc()'s prototype, use this instead:

#include <stdlib.h>
agree
>
int main()
{
char *p;
char*q;
p=(char *) malloc(100);

The cast is unnecessary, as I have already explained to you.
agree, but still its hard to unlearn the stuff learnt from book,
"malloc returns void * and you need to cast it"
>

/* I should do memset but ... */

No, you should check that the allocation succeeded before relying on it.

if(p != NULL)
{
agree,
>

strcpy(p,"raxit sheth");

That's fine.
q=p;

That's legal.
printf("\nP=%p : %s",p,p);

printf("P=%p : %s\n", (void *)p, p);
printf("\nQ=%p :%s",q,q);

printf("Q=%p : %s\n", (void *)q, q);
fflush(stdout);
free(p);

That's fine. The value that p and q shared is now indeterminate, so you
won't be able to evaluate p or q again until they've been given new
values.
/* p=NULL; */

Why comment that out?
both run commented and uncommented, belows are output of both.
>
printf("\n AFTER FREE ");
printf("\nP=%p : %s",p,p);
That's illegal, because you are using the value of an indeterminate
pointer.
Yes, I Agree, its illegal.

But here we are trying to find out some stuff on what happen/can be
done to avoid illegal access after freeing the memory,

so i think its 'Known Illegal', and that is the actual point i want
to make, ( or any good example which is legal and still show simillar
stuff. ?)

I may want to learn if we use

free(p);p=NULL;

kind of stuff, is it anyhow helpful in avoiding this type of Illegal
stuff ?

>
printf("\nQ=%p : %s",q,q);

Likewise.
return 0;
}
/* end */
output on linux box

...is irrelevant, because you broke the rules of C, so any output you
get is not bound by those rules.
we are discussing how to avoid of breaking C Rules ( or better what
may be outcome of accessing freed memory) and to explain this i need
to break the rules.(Correct me if i done wrong. or better example.)
>
Now Uncommented p=NULL in above code.

It doesn't matter. The program remains broken because you are evaluating
p and q.
I know (and agree), code is still broken.
>
I think (correct me if I am wrong, I am learning here.)
1.this technique is useful in some case but not in all where pointer
assignment is doing like this way. q is pointing to same memory
location as of p before free, and doing p=NULL is not helpful for q.

If you give q a value which later becomes indeterminate, it's your job
to make sure you don't evaluate q.
Yes, this is correct if programmer is very very very careful and Dont
work under difficult deadlines.
>
any opinion on this ? Adv/Disadv/limitation/ ?

I recommend that you study the rules of C carefully before you decide on
a programming strategy for memory management.
can you recommend good resource ?

--Raxit Sheth

Feb 14 '07 #34

P: n/a
On Feb 13, 1:38 pm, Richard Heathfield <r...@see.sig.invalidwrote:
Short of writing an entire pointer management subsystem, there isn't
much you can do with a pointer to check it for validity, but you *can*
test it against NULL. If you know it's NULL, you know it's invalid. If
it isn't NULL, you can't be sure either way. So setting it to NULL when
it would otherwise be indeterminate is a Good Thing, because it
increases the amount of information available to you at a trivial cost.
At last... this thread is finally starting to boil down to "NULL makes
a great sentinel value." ;)

-Beej

void delete_goat(GOAT *g)
{
free(g);
g = NULL;
}

Feb 14 '07 #35

P: n/a
Beej wrote:
On Feb 13, 1:38 pm, Richard Heathfield <r...@see.sig.invalidwrote:
>Short of writing an entire pointer management subsystem, there isn't
much you can do with a pointer to check it for validity, but you *can*
test it against NULL. If you know it's NULL, you know it's invalid. If
it isn't NULL, you can't be sure either way. So setting it to NULL when
it would otherwise be indeterminate is a Good Thing, because it
increases the amount of information available to you at a trivial cost.

At last... this thread is finally starting to boil down to "NULL makes
a great sentinel value." ;)

-Beej

void delete_goat(GOAT *g)
{
free(g);
g = NULL;
}
This being a place where the assignment of NULL is completely
pointless.

--
Chris "electric hedgehog" Dollin
"- born in the lab under strict supervision -", - Magenta, /Genetesis/

Feb 14 '07 #36

P: n/a
ra************@yahoo.co.in said:
On Feb 14, 2:33 pm, Richard Heathfield <r...@see.sig.invalidwrote:
>raxitsheth2...@yahoo.co.in said:
<snip>
>>
p=(char *) malloc(100);

The cast is unnecessary, as I have already explained to you.
agree, but still its hard to unlearn the stuff learnt from book,
"malloc returns void * and you need to cast it"
It's because malloc returns void * that you _don't_ need to cast it!

<snip>
printf("\n AFTER FREE ");
printf("\nP=%p : %s",p,p);
>That's illegal, because you are using the value of an indeterminate
pointer.

Yes, I Agree, its illegal.

But here we are trying to find out some stuff on what happen/can be
done to avoid illegal access after freeing the memory,
Writing programs whose output is undefined is not a good way to find
stuff out.
I may want to learn if we use

free(p);p=NULL;

kind of stuff, is it anyhow helpful in avoiding this type of Illegal
stuff ?
I find it helpful to ensure that any object pointer *either* points to a
valid object *or* has a value of NULL. If I do this, then I can be
assured that if(p != NULL) { p points to a valid object } but the price
of this assurance is that I must set p to NULL if it no longer points
to a valid object.

<snip>
>>
output on linux box

...is irrelevant, because you broke the rules of C, so any output you
get is not bound by those rules.

we are discussing how to avoid of breaking C Rules ( or better what
may be outcome of accessing freed memory) and to explain this i need
to break the rules.(Correct me if i done wrong. or better example.)
You're wrong. Breaking the rules teaches you nothing about the language,
because by breaking the rules you are giving the implementation the
freedom to provide any behaviour whatsoever, or even no behaviour
whatsoever if it prefers.

I think (correct me if I am wrong, I am learning here.)
1.this technique is useful in some case but not in all where
pointer assignment is doing like this way. q is pointing to same
memory location as of p before free, and doing p=NULL is not
helpful for q.

If you give q a value which later becomes indeterminate, it's your
job to make sure you don't evaluate q.
Yes, this is correct if programmer is very very very careful and Dont
work under difficult deadlines.
Yes, programmers do have to be very very very careful. Because deadlines
are often unrealistic, mistakes happen. With experience, you will learn
how to identify these mistakes quickly.
any opinion on this ? Adv/Disadv/limitation/ ?

I recommend that you study the rules of C carefully before you decide
on a programming strategy for memory management.

can you recommend good resource ?
ISO/IEC 9899.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 14 '07 #37

P: n/a
Chris Dollin said:
Beej wrote:
>On Feb 13, 1:38 pm, Richard Heathfield <r...@see.sig.invalidwrote:
>>Short of writing an entire pointer management subsystem, there isn't
much you can do with a pointer to check it for validity, but you
*can* test it against NULL. If you know it's NULL, you know it's
invalid. If it isn't NULL, you can't be sure either way. So setting
it to NULL when it would otherwise be indeterminate is a Good Thing,
because it increases the amount of information available to you at a
trivial cost.

At last... this thread is finally starting to boil down to "NULL
makes a great sentinel value." ;)

-Beej

void delete_goat(GOAT *g)
{
free(g);
g = NULL;
}

This being a place where the assignment of NULL is completely
pointless.
....but then it's a pointless function anyway.

I write destructors like this:

void goat_delete(GOAT **g)
{
if(g != NULL)
{
if(*g != NULL)
{
GOAT *p = *g; /* purely for notational convenience */
horn_delete(&p->horn);
trollgun_delete(&p->trollgun);
leg_delete(&p->leg);
free(p);

*g = NULL; /* *not* a pointless assignment */
}
}
}

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 14 '07 #38

P: n/a
Richard Heathfield wrote:
Chris Dollin said:
>Beej wrote:
>>void delete_goat(GOAT *g)
{
free(g);
g = NULL;
}

This being a place where the assignment of NULL is completely
pointless.

...but then it's a pointless function anyway.
It frees the store its argument points to and names what's
going on, so the /function/ isn't pointless.
I write destructors like this:

void goat_delete(GOAT **g)
{
if(g != NULL)
{
if(*g != NULL)
{
GOAT *p = *g; /* purely for notational convenience */
horn_delete(&p->horn);
trollgun_delete(&p->trollgun);
leg_delete(&p->leg);
free(p);

*g = NULL; /* *not* a pointless assignment */
}
}
}
Interesting. I'm trying to articulate why I find that overkill.
I /think/ it's that where I free something, either the place
I'm freeing it from is about to evaporate (as in your horn,
leg, and trollgun), so the assignment doesn't help, or I'm
about to assign a new value to that place, ditto. Probably because
we're writing different kinds of code. With a shared goal:
"don't let invalid pointers screw you up - get rid of them PDQ".

--
Chris "electric hedgehog" Dollin
A rock is not a fact. A rock is a rock.

Feb 14 '07 #39

P: n/a
[some re-flow]
Chris Dollin said:
Richard Heathfield wrote:
>Chris Dollin said:
>>Beej wrote:
void delete_goat(GOAT *g) { free(g); g = NULL; }

[...] where the assignment of NULL is completely pointless.

...but then it's a pointless function anyway.

It frees the store its argument points to and names what's
going on, so the /function/ isn't pointless.
free(whatever_you_would_have_passed_to_delete_goat ); would do the same
trick, though - it frees the memory and (if the pointer is well-named)
documents what's going on as well, to anyone who knows what free() is
for - and if they don't know, why are we letting them touch production
code?
>I write destructors like this:

void goat_delete(GOAT **g)
{
if(g != NULL)
{
if(*g != NULL)
{
GOAT *p = *g; /* purely for notational convenience */
horn_delete(&p->horn);
trollgun_delete(&p->trollgun);
leg_delete(&p->leg);
free(p);

*g = NULL; /* *not* a pointless assignment */
}
}
}

Interesting. I'm trying to articulate why I find that overkill.
I /think/ it's that where I free something, either the place
I'm freeing it from is about to evaporate (as in your horn,
leg, and trollgun), so the assignment doesn't help,
It might not only be goats that use trollguns, and anyway there may be
other circumstances where you need to destroy a trollgun other than the
one where you are destroying - sorry! deleting - a goat.
[...] Probably because
we're writing different kinds of code. With a shared goal:
"don't let invalid pointers screw you up - get rid of them PDQ".
Yeah. The thing is, different people think in different ways. There's
more than one way to do it, as the Perl people are so fond of reminding
us - and what seems natural and elegant to one person may well seem
kludge-ugly to another. There are lots of right ways. (And vastly more
wrong ways...)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 14 '07 #40

P: n/a
Richard Heathfield wrote:
[some re-flow]
Chris Dollin said:
>Richard Heathfield wrote:
>>Chris Dollin said:
Beej wrote:
void delete_goat(GOAT *g) { free(g); g = NULL; }

[...] where the assignment of NULL is completely pointless.

...but then it's a pointless function anyway.

It frees the store its argument points to and names what's
going on, so the /function/ isn't pointless.

free(whatever_you_would_have_passed_to_delete_goat ); would do the same
trick, though - it frees the memory and (if the pointer is well-named)
documents what's going on as well, to anyone who knows what free() is
for - and if they don't know, why are we letting them touch production
code?
When goats are given additional pointer members (such as arms),
freeing a goat will have to deal with this. I find it easiest
to have a goatFree function right from the start, so that
I don't have to go free(aGoat)-hunting and change it. Calling
`free` directly risks forgetting to handle the insides ...

(destructor snipped)
>Interesting. I'm trying to articulate why I find that overkill.
I /think/ it's that where I free something, either the place
I'm freeing it from is about to evaporate (as in your horn,
leg, and trollgun), so the assignment doesn't help,

It might not only be goats that use trollguns, and anyway there may be
other circumstances where you need to destroy a trollgun other than the
one where you are destroying - sorry! deleting - a goat.
Yes - but the same argument applies: either I'm going to destroy
the place that pointed to the gun, so no point nulling it, or I'm
going to give it a new value, so no point nulling it. That's the way
my code seemed to turn out, anyway.

[I write very little C these days: s'mostly Java. It's amusing
how each language highlights issues with the other ...]
>[...] Probably because
we're writing different kinds of code. With a shared goal:
"don't let invalid pointers screw you up - get rid of them PDQ".

Yeah. The thing is, different people think in different ways.
So true. Not all different ways are bonkers.

--
Chris "electric hedgehog" Dollin
"Who are you? What do you want?" /Babylon 5/

Feb 14 '07 #41

P: n/a
On Feb 14, 4:00 pm, Richard Heathfield <r...@see.sig.invalidwrote:
raxitsheth2...@yahoo.co.in said:
On Feb 14, 2:33 pm, Richard Heathfield <r...@see.sig.invalidwrote:
raxitsheth2...@yahoo.co.in said:

<snip>
p=(char *) malloc(100);
The cast is unnecessary, as I have already explained to you.
agree, but still its hard to unlearn the stuff learnt from book,
"malloc returns void * and you need to cast it"

It's because malloc returns void * that you _don't_ need to cast it!

<snip>
printf("\n AFTER FREE ");
printf("\nP=%p : %s",p,p);
That's illegal, because you are using the value of an indeterminate
pointer.
Yes, I Agree, its illegal.
But here we are trying to find out some stuff on what happen/can be
done to avoid illegal access after freeing the memory,

Writing programs whose output is undefined is not a good way to find
stuff out.
I may want to learn if we use
free(p);p=NULL;
kind of stuff, is it anyhow helpful in avoiding this type of Illegal
stuff ?

I find it helpful to ensure that any object pointer *either* points to a
valid object *or* has a value of NULL. If I do this, then I can be
assured that if(p != NULL) { p points to a valid object } but the price
of this assurance is that I must set p to NULL if it no longer points
to a valid object.

<snip>
output on linux box
...is irrelevant, because you broke the rules of C, so any output you
get is not bound by those rules.
we are discussing how to avoid of breaking C Rules ( or better what
may be outcome of accessing freed memory) and to explain this i need
to break the rules.(Correct me if i done wrong. or better example.)

You're wrong. Breaking the rules teaches you nothing about the language,
because by breaking the rules you are giving the implementation the
freedom to provide any behaviour whatsoever, or even no behaviour
whatsoever if it prefers.
i agree on most of your suggestion

may you have example that show the things and Don't Break rule for
what may be the behaviour of accessing memory after freeing even if
one SHOULD NOT access it. ?
>
I think (correct me if I am wrong, I am learning here.)
1.this technique is useful in some case but not in all where
pointer assignment is doing like this way. q is pointing to same
memory location as of p before free, and doing p=NULL is not
helpful for q.
If you give q a value which later becomes indeterminate, it's your
job to make sure you don't evaluate q.
Yes, this is correct if programmer is very very very careful and Dont
work under difficult deadlines.

Yes, programmers do have to be very very very careful. Because deadlines
are often unrealistic, mistakes happen. With experience, you will learn
how to identify these mistakes quickly.
any opinion on this ? Adv/Disadv/limitation/ ?
what may be wrong if one is knowing the sizeof allocated memory and
memset with 0, and free it (and may be assign NULL to var) ? (except
performance--i agree.)

I recommend that you study the rules of C carefully before you decide
on a programming strategy for memory management.
can you recommend good resource ?

ISO/IEC 9899.
thanks for this,
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999http://www.cpax.org.uk
email: rjh at the above domain, - www.
--Raxit

Feb 14 '07 #42

P: n/a
Chris Dollin said:

<snip>
When goats are given additional pointer members (such as arms),
freeing a goat will have to deal with this. I find it easiest
to have a goatFree function right from the start, so that
I don't have to go free(aGoat)-hunting and change it.
Yes, likewise, which is why I write the destructor in the way I showed
you.
>It might not only be goats that use trollguns, and anyway there may
be other circumstances where you need to destroy a trollgun other
than the one where you are destroying - sorry! deleting - a goat.

Yes - but the same argument applies: either I'm going to destroy
the place that pointed to the gun, so no point nulling it, or I'm
going to give it a new value, so no point nulling it.
No, there's another possibility - that the entity that had the gun no
longer has a gun (I dunno, perhaps the troll rips out the arm that was
holding it or something), and thus NULL is an appropriate value for
that pointer. For me, this is often the case, (not that I use trollguns
very often) - objects gain and lose other objects with careful abandon.

<snip>

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 14 '07 #43

P: n/a
ra************@yahoo.co.in said:

<snip>
may you have example that show the things and Don't Break rule for
what may be the behaviour of accessing memory after freeing even if
one SHOULD NOT access it. ?
I am not sure that I understand your question. Once you've freed memory,
you are no longer allowed to use it. If you *do*, the C language
doesn't say what the result will be - so it could be anything. Maybe
nothing bad will happen. Maybe your computer will crash. Maybe
California will slide into the sea. And if it *does* slide into the
sea, it won't be San Andreas's fault.

<snip>
what may be wrong if one is knowing the sizeof allocated memory and
memset with 0, and free it (and may be assign NULL to var) ? (except
performance--i agree.)
Again, I'm not sure what you mean. Once you've freed the memory, you
don't own it any more, so keep your hands off it.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 14 '07 #44

P: n/a
Richard Heathfield wrote:
Chris Dollin said:

<snip>
>When goats are given additional pointer members (such as arms),
freeing a goat will have to deal with this. I find it easiest
to have a goatFree function right from the start, so that
I don't have to go free(aGoat)-hunting and change it.

Yes, likewise, which is why I write the destructor in the way I showed
you.
>>It might not only be goats that use trollguns, and anyway there may
be other circumstances where you need to destroy a trollgun other
than the one where you are destroying - sorry! deleting - a goat.

Yes - but the same argument applies: either I'm going to destroy
the place that pointed to the gun, so no point nulling it, or I'm
going to give it a new value, so no point nulling it.

No, there's another possibility - that the entity that had the gun no
longer has a gun (I dunno, perhaps the troll rips out the arm that was
holding it or something), and thus NULL is an appropriate value for
that pointer.
Yes - sometimes the new value is null.

Sometimes, rather than nulling the pointer because you're freeing it
(well, the pointed-to object), you're freeing the pointer (ditto)
because you're nulling it [1].
For me, this is often the case, (not that I use trollguns
very often) - objects gain and lose other objects with careful abandon.
Indeed.

[1] And you know this is the only surviving usable reference.

--
Chris "electric hedgehog" Dollin
"People are part of the design. It's dangerous to forget that." /Star Cops/

Feb 14 '07 #45

P: n/a
Richard Heathfield wrote:
Yeah. The thing is, different people think in different ways. There's
more than one way to do it, as the Perl people are so fond of reminding
us - and what seems natural and elegant to one person may well seem
kludge-ugly to another. There are lots of right ways. (And vastly more
wrong ways...)
While I don't generally disagree that setting a pointer to NULL after free()
is a good idea in simple cases, I think it's still just paranoid programming
where the paranoia lies against yourself.

We have better tools these days. Valgrind it, memcheck it, <insert whatever
tool is appropriate for your platform hereand use it. I've found that in a
lot of cases rather than relying on coding OCDs it can be more efficient to
just crank it through a competent external analyzer and find the problem
fast.

Caveats:

1. You might not have a decent tool on your platform.
2. You might be finding some obscure corner case (test suite anyone?)
3. You might be using NULL as a sentinel, so it's explicit setting is
warranted (but a general macro would not be).
4. You might think using an external tool is selling out to the man.
5. You might like your OCDs.
Feb 14 '07 #46

P: n/a
Christopher Layne said:
Richard Heathfield wrote:
>Yeah. The thing is, different people think in different ways. There's
more than one way to do it, as the Perl people are so fond of
reminding us - and what seems natural and elegant to one person may
well seem kludge-ugly to another. There are lots of right ways. (And
vastly more wrong ways...)

While I don't generally disagree that setting a pointer to NULL after
free() is a good idea in simple cases, I think it's still just
paranoid programming where the paranoia lies against yourself.
Yes, you're probably right. On the other hand, I don't generally
experience pointer difficulties to the degree that some other regular
contributors to this newsgroup have suggested is the case for them (no
names, no pack drill). So I'm happy to be paranoid - it cuts down on
debugging time.

<snip>

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 14 '07 #47

P: n/a
On Feb 14, 5:35 am, Ian Collins <ian-n...@hotmail.comwrote:
If a pointer is null, you can free it as often as you like. Try to
dereference it and you'll soon know what's wrong. Dereferencing or
freeing an invalid pointer has undefined and indeterminate results.
No, if you free a pointer multiple times, than the logic of your
program
is broken at its core, and you should probably rewrite the thing from
scratch.

People have put things in place to help you deal with that before the
things get bigger - for instance, free() may issue a diagnostic if
passed
an already freed pointer.

By setting it always to NULL after free(), you're defeating their
efforts.

Also, the value of the pointer may give someone who is debugging the
program
precious clue on where the value did come from - by setting it to
NULL,
you have made it indeterminate.

My advice is not to follow expert advices and never do things just
because
they're 'safe habits' - if setting a pointer to NULL doesn't serve a
specific
purpose (e.g. you want to pass it to a function where a NULL argument
means
something - default value/allocate a buffer/etc) then don't do it.

Feb 14 '07 #48

P: n/a
Racaille said:
On Feb 14, 5:35 am, Ian Collins <ian-n...@hotmail.comwrote:
>If a pointer is null, you can free it as often as you like. Try to
dereference it and you'll soon know what's wrong. Dereferencing or
freeing an invalid pointer has undefined and indeterminate results.

No, if you free a pointer multiple times, than the logic of your
program is broken at its core, and you should probably rewrite the
thing from scratch.
Possibly.

<snip>
Also, the value of the pointer may give someone who is debugging the
program
precious clue on where the value did come from
No, because inspecting the value is not allowed. The value is
indeterminate, and inspecting it invokes undefined behaviour.
- by setting it to NULL, you have made it indeterminate.
No, by setting it to NULL, you have made it determinate!
My advice is not to follow expert advices
That's poor advice.
and never do things just because
they're 'safe habits' - if setting a pointer to NULL doesn't serve a
specific purpose (e.g. you want to pass it to a function where a NULL
argument means something - default value/allocate a buffer/etc) then
don't do it.
There *is* a specific purpose in setting a pointer to NULL - and that
purpose is to ensure that the value of the pointer is determinate and
can be tested meaningfully.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 14 '07 #49

P: n/a
On Feb 14, 3:14 pm, Richard Heathfield <r...@see.sig.invalidwrote:
Also, the value of the pointer may give someone who is debugging the
program
precious clue on where the value did come from

No, because inspecting the value is not allowed. The value is
indeterminate, and inspecting it invokes undefined behaviour.
- by setting it to NULL, you have made it indeterminate.

No, by setting it to NULL, you have made it determinate!
Please, let's stop this, it gets ridiculous. You still feign not to
get my point.
If you set it to NULL after very free(), then it could be just any
pointer
ever passed to free(), and so it is indeterminate from the point of
view of somebody trying to trace it.

I know there may be machines where just 'inspecting' a invalid pointer
(without dereferencing it) is not possible, but this is irrelevant,
since as a debugger writer I am free to use whatever machine
dependencies
I like in order to track down bugs, and I am free to take advantage of
pointers being just bitmaps/long integers is this makes things
simpler.

Feb 14 '07 #50

76 Replies

This discussion thread is closed

Replies have been disabled for this discussion.