c free() 在我调用但不在我的函数中时有效
c free() works when I call but not in my function
我正在学习 C,正在玩 malloc 和 free。但是由于某种原因,当我在主要的地方使用 free() 时,一切正常,但是当我把它放在我的函数中时,它却没有
#include <stdlib.h>
#include <stdio.h>
struct st {
int number;
};
void del(struct st *s) {
if (s == NULL) return;
free(s); s = NULL;
}
int main() {
struct st *s;
s = (struct st *)malloc(sizeof(struct st));
s->number = 4;
printf("The value is: %d", s->number);
del(s);
// free(s); s= NULL;
if(s == NULL) printf("\nThe struct is removed from memory\n");
else printf("\nThe value is: %d\n", s->number);
return 0;
}
这个回显:
The value is: 4
The value is: 0
但如果我这样做:
// del(s);
free(s); s= NULL;
有效
您正在将指针传递给您的函数,这意味着它只能访问该指针的本地副本。因此,您的 free(s)
将仅释放此本地副本。如果你想释放一个变量,它在你调用 free
的函数的范围之外,你需要通过再次取消引用(传递一个指向这个指针的指针)来访问它。
void del(struct st **s) {
if (*s == NULL) return;
free(*s);
*s = NULL;
}
应该可以正常工作。
编辑:通过del(&s)
调用函数;
您的 del 函数释放分配的内存并将 NULL 分配给变量的本地副本。但是,本地副本与调用站点的副本不同(即使两者都指向同一个已分配的对象,已被释放)。
然后你最终会做所谓的 "use after free()",这在这种特定情况下(可能)不会产生积极的危害,但在一般情况下可能是一个崩溃错误(并且可能是代码注入的向量和攻击)。
要么重写 del
以获取指向指针的指针并将 &s
传入,或者让 del
return "the new value" 并执行 s = del(s)
.
我正在学习 C,正在玩 malloc 和 free。但是由于某种原因,当我在主要的地方使用 free() 时,一切正常,但是当我把它放在我的函数中时,它却没有
#include <stdlib.h>
#include <stdio.h>
struct st {
int number;
};
void del(struct st *s) {
if (s == NULL) return;
free(s); s = NULL;
}
int main() {
struct st *s;
s = (struct st *)malloc(sizeof(struct st));
s->number = 4;
printf("The value is: %d", s->number);
del(s);
// free(s); s= NULL;
if(s == NULL) printf("\nThe struct is removed from memory\n");
else printf("\nThe value is: %d\n", s->number);
return 0;
}
这个回显:
The value is: 4
The value is: 0
但如果我这样做:
// del(s);
free(s); s= NULL;
有效
您正在将指针传递给您的函数,这意味着它只能访问该指针的本地副本。因此,您的 free(s)
将仅释放此本地副本。如果你想释放一个变量,它在你调用 free
的函数的范围之外,你需要通过再次取消引用(传递一个指向这个指针的指针)来访问它。
void del(struct st **s) {
if (*s == NULL) return;
free(*s);
*s = NULL;
}
应该可以正常工作。
编辑:通过del(&s)
调用函数;
您的 del 函数释放分配的内存并将 NULL 分配给变量的本地副本。但是,本地副本与调用站点的副本不同(即使两者都指向同一个已分配的对象,已被释放)。
然后你最终会做所谓的 "use after free()",这在这种特定情况下(可能)不会产生积极的危害,但在一般情况下可能是一个崩溃错误(并且可能是代码注入的向量和攻击)。
要么重写 del
以获取指向指针的指针并将 &s
传入,或者让 del
return "the new value" 并执行 s = del(s)
.