Re: Setting malloc pointer to NULL?

Tech-Archive recommends: Fix windows errors by optimizing your registry



Robby wrote:
ooh man, Im getting some weird stuff happening here!

Let me ask you guys something. After you free a pointer that was created with malloc (which set aside memory in the heap for a struct) should we set that pointer to NULL ?

If you're unsure of others who might again try to free it, yes, you should. If you need to free the memory ASAP and then you need to know whether it's been freed, then the NULL is a very good indicator (you can test for it in an 'if'). If you're concerned with calling 'free' more than once, then, in most cases, it's better to eliminate even the possibility of double freeing by writing *correct code*. Let the memory be allocated until you need to re-allocate, and only free right before setting it to a new value. Or free it right before the pointer variable goes out of scope, then the danger of double freeing will subside...

Theoretical general questions like yours are difficult to answer with any reasonable degree of certainty. Perhaps you want to provide the context or the circumstances that prompted your question...

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
.



Relevant Pages

  • Re: ptrs validity
    ... I have a pointer that points to an unknown heap memory block, ... hardware checked segment for each allocation. ...
    (comp.lang.c)
  • Re: What Kind of DataStructures C using? ( Heap or Tree ??)
    ... > Some were said heap, ... instructions and data is put on a stack. ... reserve memory on the heap and ... return a pointer to this memory area. ...
    (comp.lang.c)
  • Re: Tech directions for Delphi?
    ... Nope, the gen 0 heap isn't just a bunch of pointers in a graph, it's also data bytes kept together so that you can perform incremental allocations. ... It's the same with FastMM, you just have less hoops around advancing the pointer. ... > of event logs) are commonly used but are a small proportion of apps written. ... The old memory manager could turn into an absolute horror in multithreading. ...
    (borland.public.delphi.non-technical)
  • Re: loading csv-files: too much memory-consumption
    ... contain an assumed pointer to heap data. ... to see the memory map of your lisp implementation. ... use this kind of non-initializing memory allocation, the probability ...
    (comp.lang.lisp)
  • Re: Is this math test too easy?
    ... > communications glitch; one of the more laughable cartoons ... it was loaded into physical memory and, ... > Or one can interpret the character string as one of the values ... A pointer to an integer? ...
    (sci.math)