Re: assigning pointer to NULL



"Joachim Schmitz" <nospam.jojo@xxxxxxxxxxxxxxxxxx> writes:
Chris Dollin wrote:
karthikbalaguru wrote:
On Jan 31, 5:15 am, "Roman Mashak" <m...@xxxxxxxx> wrote:
is it legal to destroy the memory pointed to by a pointer and then
assign NULL to it? Say, like this:

char *ptr;
ptr = malloc(10);
free(ptr);

Here, ptr will become a Dangling Pointer.

ptr = NULL;


By this assignment of NULL, ptr will no longer be a dangling pointer.

This is a very important step to be followed while freeing .

This is /sometimes/ an important step. At other times, it's
mindblowingly pointless. It depends, for example, on whether
there are other ways to get to the pointer variable (if not,
assigning null to it is pointless) and whether those other
ways bother to check for null (in which case you have problems
regardless).
Not quite: you program will crash right there, when dereferencing the NULL
pointer, rather than at some other obscure and random place, so this helps
in detecting the bug.

Probably. There's no guarantee that an attempt to dereference a null
pointer will be detected at run time, (though it will be on most
systems).

--
Keith Thompson (The_Other_Keith) <kst-u@xxxxxxx>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.



Relevant Pages

  • Re: Typecasting pointers
    ... array of shorts, and initialize them all to the same value. ... You're saving the value of ptr so you can freeit later. ... A pointer increment advances the pointer by one object size, ... optimizing compiler could have done a better job than you have. ...
    (comp.lang.c)
  • RE: Multiple pointer entry`s for pc`s
    ... Pointer (PTR) RRs are used to support the reverse ... resolve this information to the DNS domain name for that computer. ... PTR RRs can be added to a zone in several ways: ...
    (microsoft.public.win2000.dns)
  • Re: use delete to destroy primitive/object types but memory is not freed
    ... the safest approach is to think of a pointer as an opaque ... The call to mallocallocates memory space for a double object; ... We then assign a value to the double object that ptr points to, ... The C runtime system has reserved that chunk of memory, ...
    (comp.lang.c)
  • Re: How to know the memory pointed by a ptr is freed?
    ... Section 3.3.4 of the C89 standard expressly allows conversions between ... the integer type is wide enough to hold a pointer. ... The pointer might be loaded in to an address register causing the ... Why would the contents of "ptr" be placed into an address ...
    (comp.lang.c)
  • Re: How to know the memory pointed by a ptr is freed?
    ... > And what about the 37 copies made of that pointer after it was ... the value of "ptr" ... pattern stored in "ptr", or does it mean that we cannot under any ... that we gave that memory back to the system and any access to it ...
    (comp.lang.c)