can't delete a memory location
#include <stdio.h>
#include <stdlib.h>
typedef struct data {
int a, b;
} Data ;
struct node {
Data info;
int priority;
struct node *link;
};
typedef struct node* Node;
void insert(Node header, int pr, Data el) {
Node cur = header;
Node tmp = malloc(sizeof(struct node));
tmp->info = el;
tmp->priority = pr;
//descending <=
while (cur->link != NULL && pr >= cur->link->priority)
cur = cur->link;
tmp->link = cur->link;
cur->link = tmp;
}
Node delete(Node header) {
Node tmp;
if (header->link == NULL)
printf("Empty priority queue");
else {
tmp = header->link;
header->link = tmp->link;
free(tmp);
return tmp;
}
}
void display(Node head) {
开发者_JS百科 Node cur = head->link;
while (cur != NULL) {
printf("%d ", cur->priority);
cur = cur->link;
}
}
int main(int argc, const char *argv[])
{
Data d;
Node tmp;
Node head = malloc(sizeof(struct node));
head->link = NULL;
insert(head, 3, d);
insert(head, 2, d);
insert(head, 1, d);
while (head->link != NULL) {
tmp = delete(head);
printf("%d ", tmp->priority);
}
return 0;
}
The output of this is 1 2 3. but in delete i deallocated the memory(free(tmp)) and then returned tmp. why is it tmp still printing in main function. using gcc compiler
delete
/free
don't necessarily zero out memory. They can mark it as deallocated for the memory allocator. The memory allocator is then free to allocate it again in another new
/malloc
call. The point is, as soon as you freed the memory block, you should not access it. It's undefined behavior. Undefined behavior means it may crash, return garbage, return old value, blow up your computer, become a skynet, or anything else, depending on the implementation/situation.
If you want to store sensitive information like cryptographic keys/passwords in memory as short as possible, you should fill the memory with something else yourself before freeing it up (e.g. by calling SecureZeroMemory
in Windows).
精彩评论