0

I use only main() function. Not copying any pointer. Why free() function not get NULL value? Whay I can check my wariable is full or empty?

#include <stdio.h>
#include <stdlib.h>

int main()
{
int *e = NULL;

 printf("before e=%p\n",(void *)e);
 e = malloc(sizeof(int));
 *e = 7;
 printf("after,  e=%p\n",(void *)e);
 if(e == NULL) { printf("Problemy z pamięcia\n"); return 0; }
 printf(" value = %d\n",*e);

 free(e);
 printf("after free,  e=%p\n",(void *)e);
 if(e == NULL) printf("is NULL\n");

return 1;
}

result

before e=0
after,  e=464027a0
 value = 7
after free,  e=0x7f82464027a0

why if(e==NULL) is not true? How do it?

1 Answers1

4

Because C has a call-by-value policy and free is a standard function. Every function call is not modifying its arguments, because formal parameters hold a copy of the argument passed at the call.

In practice, you could use the comma operator and systematically do

  free(e), e = NULL;

However, using a pointer (value) after it has been free-d is undefined behavior. Be scared of UB, so learn more about it.

You should compile with all warnings and debug info (so gcc -Wall -Wextra -g if using GCC) and learn to use the gdb debugger. You could use tools like valgrind or address sanitizers, since they are very helpful to hunt bugs such as memory leaks or buffer overflows.

BTW, your code is wrong. You don't test against failure of malloc (your if(e == NULL) is too late, and the preceding *e = 7; is likely to get a segmentation fault when malloc has failed) , and you really should code at least something like:

 e = malloc(sizeof(int));
 if (!e) { perror("malloc e"); exit(EXIT_FAILURE); };

The !e above could be replaced by e==NULL for readability.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547