如果我向函数传递一个指针,其中指针获取分配给的内存的地址,那么当函数退出时,内存是否释放?
void initWomenList(Women **head, Women *headWoman) {
headWoman = (Women *) malloc(sizeof(Women));
if (headWoman == NULL) {
printf("Allocation of headWoman failedn");
exit(1);
}
headWoman->userWoman = NULL;
headWoman->next = NULL;
head = &headWoman;
}
当函数返回时,头和头女人都为空吗?
C 语言中没有自动内存释放(有时称为垃圾回收器)。分配了malloc/calloc/realloc
的任何内存都必须使用free
函数手动释放。
C 语言中的所有函数参数都是按值传递的,因此在函数内部分配headWomen
在函数外部不起作用,并且当前您有内存泄漏,因为没有指针保存分配的内存。
void
alloc_mem(int* a) {
a = malloc(sizeof(*a));
}
//usage in your case
int* a;
//Function will allocate memory for single int, but it won't be saved to variable a.
alloc_mem(a);
更好的方法是使用指针到指针或从函数返回指针。
int*
alloc_mem() {
return malloc(sizeof(int));
}
//usage
int* a = alloc_mem();
if (a != NULL) {
//Check if null
}
或者使用指针到指针的方法
void
alloc_mem(int** a) {
*a = malloc(sizeof(**a));
}
//usage
int* a;
alloc_mem(&a);
if (a != NULL) {
//Do the job.
}
在所有这些操作结束时,始终调用free
函数
free(a);
如果我回到你最初的例子,你必须将函数重写成这样的东西:
void
//Notice here **headWoman instead of *headWoman
initWomenList(Women **head, Women **headWoman) {
//Notice here *headWoman instead of headWoman
*headWoman = malloc(sizeof(Women));
if (headWoman == NULL) {
printf("Allocation of headWoman failedn");
exit(1);
}
headWoman->userWoman = NULL;
headWoman->next = NULL;
//Notice here *head instead of head
*head = &headWoman;
}
和用法:
Woman* headWoman;
Woman* head;
initWomenList(&head, &headWoman);
//Don't forget to free memory after usage.