#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) {
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;
}
Run Code Online (Sandbox Code Playgroud)
这个输出是1 2 3.但在删除时我释放了内存(free(tmp))然后返回tmp.为什么tmp仍然在主要功能中打印.使用gcc编译器
delete/ free不一定将内存清零.他们可以将其标记为内存分配器的解除分配.然后,内存分配器可以在另一个new/ malloc调用中再次分配它.关键是,一旦释放了内存块,就不应该访问它.这是未定义的行为.未定义的行为意味着它可能会崩溃,返回垃圾,返回旧值,炸毁您的计算机,变成天网或其他任何东西,具体取决于实施/情况.
如果要将加密密钥/密码等敏感信息尽可能短地存储在内存中,则应在释放内存之前自己填充其他内容(例如,通过SecureZeroMemory在Windows中调用).
| 归档时间: |
|
| 查看次数: |
181 次 |
| 最近记录: |