LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

How to tell if a pointer (to malloc-ed memory) has already been freed

Given:
  struct DBRESULTS *pDBResults;
pDBResults = (struct DBRESULTS *)malloc(sizeof(struct DBRESULTS))
 
      if (pDBResults != NULL)
        free (pDBResults);
The test for whether to free or not will pass regardless of whether the memory has already been freed.  In other words, I do this when I'm finished, but I also have this as the program is exiting in case there was a problem and the program is shutting down outside the normal sequence.  When the normal sequence IS followed, the first occurance frees the memory, and the second occurance tries to and gives an error (because it is attempting to free a pointer already freed).
 
How can I test the pointer to tell whether it has already been freed or not?
0 Kudos
Message 1 of 4
(3,641 Views)

Clearing your pointer when you free the memory should do the trick:

  if (pDBResults != NULL)
        { free (pDBResults);

          pDBResults=NULL;

        }
  

0 Kudos
Message 2 of 4
(3,637 Views)
You can embed all the process in a macro that checks for the variable, clears it and frees the pointer:
 
#define ClearMem(xx) if (xx) { free (xx); xx = NULL; }


Proud to use LW/CVI from 3.1 on.

My contributions to the Developer Community
________________________________________
If I have helped you, why not giving me a kudos?
0 Kudos
Message 3 of 4
(3,624 Views)
Many thanks to MVR and Roberto for your help.  Most of my attempts at programming is under Visual Studio, but I still enjoy revisiting my roots of where I learned C.  With this new info, I'm assuming that Microsoft does these two steps in one, and I've grown accustomed to the crutch.  Thanks for steering me back on track!
0 Kudos
Message 4 of 4
(3,597 Views)