简体   繁体   中英

Freeing a pointer to structure containing an array

I have some issues, maybe coming from a misunderstanding of how the function "free" works. Basically I have defined a structure like this

typedef char parola[11]
typedef struct _node node
struct _node
{
  parola wrd;
  node *padre;
  node *Ts;
  node *Td;
};

Later in the code I allocate memory for a node using malloc:

node *r
r = (node *) malloc(sizeof(node));

And i create binary search trees allocating memory for every single node in this way. When I try to remove a node in a bst, I pass a pointer to that node *n. I think I nail the recursive procedure, but then when it comes to using free() on the pointer to the node, that doesn't seem to work. I am sure of it because if I try to print "parola" in the node, it does actually print the word that was contained there after deallocating the memory.

node *n

.../*in another function*/

free (n)

printf("%s\n",n->wrd)
/*This does print the word inside the node after the deallocation*/

What am I missing here? Do i need to use free() in a different way?

Thanks for your help.

In C, free doesn't wipe the data. It just says "I'm not using it any more; you can use it for something else." If nothing needs to use it in that time, it won't be overwritten.

However, you can't guarantee that it won't be overwritten. Using stuff after it's free d is an excellent way to have your program suddenly, unpredictably fail at the worst possible moment.

(Make sure you free the node(s) you're pointing to before you throw away (or free) their last pointer(s), and make sure you only free each thing once!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM