在C中是否有任何方法可以知道以前是否已使用free()释放了内存块?我能做点什么......
if(isFree(pointer))
{
//code here
}
Run Code Online (Sandbox Code Playgroud)
好的,如果您需要检查指针是否已被释放,您可能需要检查您的设计.您永远不必跟踪指针上的引用计数或是否已释放它.另外一些指针不是动态分配的内存所以我希望你的意思是用malloc()调用的.这是我的意见,但如果你有一个坚实的设计,你应该知道你的指针指向的东西何时被使用.
我看到的唯一不起作用的地方是单片内核,因为内存中的页面需要使用次数,因为共享映射等等.
在您的情况下,只需将未使用的指针设置为NULL并检查.如果您在malloced结构中有未使用的字段,这将为您提供一种保证的方式.一个简单的规则是,无论何时释放需要以上述方式检查的指针,只需将其设置为NULL,并使用if = = NULL替换isFree().这样就不需要跟踪引用计数,并且您确定指针是否有效并且没有指向垃圾.
不,没有办法.
但是,您可以使用一些代码规则,如下所示:
永远永远 永远守护使用malloc分配:
void * vp;
if((vp = malloc(SIZE))==NULL){
/* do something dreadful here to respond to the out of mem */
exit(-1);
}
Run Code Online (Sandbox Code Playgroud)
释放指针后,将其设置为0
free(vp); vp = (void*)0;
/* I like to put them on one line and think of them as one peration */
Run Code Online (Sandbox Code Playgroud)
只要说,你可以尝试使用你的"被释放"功能的任何地方
if(vp == NULL)[
/* it's been freed already */
}
Run Code Online (Sandbox Code Playgroud)
@Jesus在评论中说:
我不能真正推荐这个,因为一旦你完成了那个内存,指针应该立即超出范围(或至少在释放它的函数的末尾)这些悬挂指针存在只是不正确与我一起.
在可能的情况下,这通常是很好的做法; 问题是在C的现实生活中往往是不可能的.以一个包含双向链接列表的文本编辑器为例.列表非常简单:
struct line {
struct line * prev;
struct line * next;
char * contents;
}
Run Code Online (Sandbox Code Playgroud)
我定义了一个guarded_malloc分配内存的函数
void * guarded_malloc(size_t sz){
return (malloc(sz)) ? : exit(-1); /* cute, eh? */
}
Run Code Online (Sandbox Code Playgroud)
并使用.创建列表节点 newLine()
struct line * newLine(){
struct line * lp;
lp = (struct line *) guarded_malloc(sizeof(struct line));
lp->prev = lp->next = lp-contents = NULL ;
return lp;
}
Run Code Online (Sandbox Code Playgroud)
我在字符串中添加文字s到我的行
lp->contents = guarded_malloc(strlen(s)+1);
strcpy(lp->contents,s);
Run Code Online (Sandbox Code Playgroud)
并且不要狡辩我应该使用有界长度的形式,这只是一个例子.
现在,如何在释放后实现删除line我创建的内容char * contents?