0

Is there a way to check if a pointer has been free before?

For example, if I run this code:

int* p = (int*)malloc(1000);
free(p);
p = (int*)realloc(p, 2000);

I get the error:

*** Error in `./main': realloc(): invalid old size: 0x00000000012ab010 ***
...

I would like to have an opportunity to check p before calling realloc to avoid such errors.

Fomalhaut
  • 8,590
  • 8
  • 51
  • 95
  • 1
    There is no need to cast the return of `malloc` or `realloc` (or `calloc`), it is unnecessary. See: [Do I cast the result of malloc?](http://stackoverflow.com/q/605845/995714) – David C. Rankin Aug 16 '18 at 02:49

1 Answers1

9

Here's how you check: Did you free it before? If so, it's been freed. If not, no.

C doesn't track this for you, so you may want to NULL out any pointers you free if you lose track of if you have or haven't released the associated memory.

C does the most minimal thing unless you spell out explicitly that you want it to do something more:

free(p);
p = NULL;

Now you can test, but remember, it's your responsibility to do this, so if this behaviour is important, you must do it consistently.

tadman
  • 208,517
  • 23
  • 234
  • 262