【发布时间】:2020-12-10 13:44:15
【问题描述】:
我知道每次我使用 malloc 或 calloc 时,我还必须释放该内存,但在这种特定情况下,我无法理解何时释放内存以及如何释放内存,如果我在 generate() 函数内释放,代码不会不再工作了。
void generate(int n){
node *tmp,*new;
int num,i;
head = malloc(sizeof(node));
if (head==NULL){
perror("malloc");
EXIT_FAILURE;
}
num = rand() % (42 - (-42) + 1) - 42;
head->data = num;
head->next = NULL;
tmp = head;
for(i=1;i<n;i++){
new = malloc(sizeof(node));
if(new == NULL){
perror("malloc");
EXIT_FAILURE;
}
num = rand() % (42 - (-42) + 1) - 42;
new->data = num;
new->next = NULL;
tmp->next = new;
tmp = tmp->next;
}
}
int main(){
int n;
do {
printf("give me the size of the linked list (less than 42):");
scanf("%d",&n);
if(n>42){
printf("i said less than 42. \n Please ");
}
} while(n>41);
srand(time(NULL));
generate(n);
printlist();
return 0;
}
【问题讨论】:
-
你需要在
generate之外释放,在所有与列表相关的任务完成后。最好将列表头传递给一个专用函数,该函数反过来会释放资源
标签: c linked-list dynamic-memory-allocation free