Connecting Tech Pros Worldwide Help | Site Map

free()ing a pointer

Markus's Avatar
Moderator
 
Join Date: Jun 2007
Location: York, England, with wolves.
Posts: 4,936
#1: 4 Weeks Ago
If we free() a pointer, is the pointer free()d or the memory the pointer points to?

Expand|Select|Wrap|Line Numbers
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include "stack.h"
  4.  
  5. void stack_new(stack *st) 
  6. {
  7.     st->log_len = 0;
  8.     st->alloc_len = 4;
  9.     st->elems = malloc(4 * sizeof(int));
  10. }
  11.  
  12. void stack_dispose(stack *st)
  13. {
  14.     free(st->elems);
  15. }
  16.  
  17. stack *stack_newx(void)
  18. {
  19.     stack *st = (stack *)malloc(sizeof(stack));
  20.     stack_new(st);
  21.     return st;
  22. }
  23.  
  24. void stack_disposex(stack *st)
  25. {
  26.     free(st); // Does this free the pointer or memory?
  27. }
Edit: since this pointer points to the memory, I guess it will free the memory. *stupid*.

Mark.
Newbie
 
Join Date: Feb 2009
Location: Chennai, India
Posts: 8
#2: 4 Weeks Ago

re: free()ing a pointer


when a pointer is freed the memory it pointing to is freed...after freeing also the pointer points to that particular location in memory.
Markus's Avatar
Moderator
 
Join Date: Jun 2007
Location: York, England, with wolves.
Posts: 4,936
#3: 4 Weeks Ago

re: free()ing a pointer


Quote:

Originally Posted by sumeshnb View Post

when a pointer is freed the memory it pointing to is freed...after freeing also the pointer points to that particular location in memory.

Right. I get that. So, after the memory pointed to is freed, the pointer still points to that memory location?
drhowarddrfine's Avatar
Expert
 
Join Date: Sep 2006
Posts: 5,561
#4: 4 Weeks Ago

re: free()ing a pointer


Yes. The pointer still exists and still points to that location.
Markus's Avatar
Moderator
 
Join Date: Jun 2007
Location: York, England, with wolves.
Posts: 4,936
#5: 4 Weeks Ago

re: free()ing a pointer


Quote:

Originally Posted by drhowarddrfine View Post

Yes. The pointer still exists and still points to that location.

Thanks, Doc.
Expert
 
Join Date: Mar 2008
Location: Naperville, Illinois U.S.
Posts: 828
#6: 4 Weeks Ago

re: free()ing a pointer


Some of the confusion comes from using the phrase "freeing a pointer". This phrase certainly gives the impression that the pointer itself is being freed. Since that is not the case, I suggest you avoid using that phrase.

The code snippet in the OP "called function free(), passing it the value of a pointer". The result was to free the memory pointed to by the pointer variable.
drhowarddrfine's Avatar
Expert
 
Join Date: Sep 2006
Posts: 5,561
#7: 4 Weeks Ago

re: free()ing a pointer


And to add the obvious, the same pointer can be used to point to new allocated memory or anything else of the same type.
Reply