-1

I am coding a program where a pointer STR *pt to a STR type structure that I am using (basically an array of STR structures with which I want to use dynamic memory) might takes a NULL value as sometimes I don't want to store any array trough it, so when I use free(pt) over that pointer I get a segmentation fault. What I want is to check it that pointer has a NULL value, but when I check if(pt != NULL) free(pt); (I only want to free memory when pointer is not NULL), condition is always true, pointer is tryed to be freed and segmentation fault happens.

Is there any way to solve this problem? Another way to compare pointer values?

  • 1
    The `free(NULL)` you mention does not cause a fault, it is caused by trying to `free` a pointer whose value was not obtained from `malloc` etc. Welcome to StackOverflow! Please post a [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example), the shortest complete code that shows the problem. – Weather Vane Dec 05 '20 at 16:53
  • Do you happen to be using a toolchain from the 1990s? – Joshua Dec 05 '20 at 17:00
  • Possible duplicate: https://stackoverflow.com/questions/3923290/heap-corruption-in-c/3923306#3923306 – Joshua Dec 05 '20 at 17:03
  • Your problem isn't because `pt` is NULL but it's invalid (e.g. heap corruption, you modified the pointer original returned by *alloc, etc). – P.P Dec 05 '20 at 17:05

2 Answers2

0

Your check looks correct; free() should not fail if passed a non-null pointer to a heap-allocated structure.

Where does the value of 'pt' come from? Did you get it from malloc()?

If you have not already, it's probably worth using GDB to verify a NULL pointer here is really causing your problem.

Lee Marshall
  • 302
  • 1
  • 3
  • `free(NULL)` is completely legal and harmless, so the test is useless. – Weather Vane Dec 05 '20 at 16:57
  • Hah; I never knew that, but right you are. To be pedantic, I came across this https://stackoverflow.com/a/46825852/6791142 . So I suppose if(pt) should not be relied upon. – Lee Marshall Dec 05 '20 at 17:11
  • The value of `STR *pt` comes from a memory allocation *in the case it previously happened*, the thing it that in the opposite case I supposed a `NULL` would have been stored. Is there any way to check if a memory allocation has been produced? – JuanSarraceno Dec 05 '20 at 17:15
  • You might be interested in [Is NULL always false?](https://stackoverflow.com/questions/459743/is-null-always-false) – Weather Vane Dec 05 '20 at 17:16
0

You can only use free() on memory allocated by malloc,calloc or realloc.First you have to assign it some memory then check

if(pt)
{
    free(pt)
}
Aniket Bose
  • 55
  • 1
  • 8