Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C中的unlink函数是否也释放内存?_C_Memory Management_Unlink - Fatal编程技术网

C中的unlink函数是否也释放内存?

C中的unlink函数是否也释放内存?,c,memory-management,unlink,C,Memory Management,Unlink,我在其中一个程序中浏览了一段代码,它使用了一个unlink函数,其中 hist_name = malloc(128) 但是,我注意到程序没有使用“free”来释放内存,但在程序结束时,它确实具有如下所示的取消链接功能: unlink(hist_name); 我的问题是,取消链接功能除了删除指向文件的链接外是否还释放内存,或者我是否仍然需要插入free(hist_name)语句来释放内存?取消链接不会释放内存。如果要释放hist\u name指向的内存,应将地址传递到freeunlink()删

我在其中一个程序中浏览了一段代码,它使用了一个unlink函数,其中

hist_name = malloc(128)
但是,我注意到程序没有使用“free”来释放内存,但在程序结束时,它确实具有如下所示的取消链接功能:

unlink(hist_name);

我的问题是,取消链接功能除了删除指向文件的链接外是否还释放内存,或者我是否仍然需要插入
free(hist_name)
语句来释放内存?

取消链接
不会释放内存。如果要释放
hist\u name
指向的内存,应将地址传递到
free

unlink()
删除文件。更具体地说,它将取消给定名称与磁盘上内容的链接,并且当没有更多名称链接到某些内容时,该内容将自动回收(即,文件将被真正删除)


它不会释放任何内存。使用
free()。但是,在程序结束之前释放内存对典型的操作系统来说并不重要,它会自动回收进程终止时使用的所有内存。

否。
hist_name
泄漏<代码>取消链接
不会释放参数

创建一个名为“a”的文件并运行此代码(使用
gcc test.c
编译):

绝对丢失:1个块中有128字节

这意味着,您分配了一次128字节的内存,但没有释放它。=>取消链接不会为您释放内存。

简短回答-否


unlink
功能仅更改文件系统,而不是堆或分配的内存。

重新“删除文件名”:
unlink
删除指向文件的链接,如果没有指向该文件的其他链接,并且没有进程打开该文件,则会删除该文件。(文件可以从多个目录链接到。)它不会删除文件名。如果要使用计算机,必须明确具体的概念。
unlink
无法在
hist_name
处释放内存,因为字符串可能根本没有被动态分配;例如,它可以是字符串文字。没有(可移植的)方法仅仅从一个地址来判断内存是如何分配的。
#include <unistd.h>
#include <stdlib.h>

int main(void){
    char* hist_name=malloc(128);
    //Fill hist_name
    hist_name[0]='a';
    hist_name[1]='\0';
    unlink(hist_name);
}
==2155== Memcheck, a memory error detector
==2155== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==2155== Using Valgrind-3.16.1 and LibVEX; rerun with -h for copyright info
==2155== Command: ./a.out
==2155== 
==2155== 
==2155== HEAP SUMMARY:
==2155==     in use at exit: 128 bytes in 1 blocks
==2155==   total heap usage: 1 allocs, 0 frees, 128 bytes allocated
==2155== 
==2155== LEAK SUMMARY:
==2155==    definitely lost: 128 bytes in 1 blocks
==2155==    indirectly lost: 0 bytes in 0 blocks
==2155==      possibly lost: 0 bytes in 0 blocks
==2155==    still reachable: 0 bytes in 0 blocks
==2155==         suppressed: 0 bytes in 0 blocks
==2155== Rerun with --leak-check=full to see details of leaked memory
==2155== 
==2155== For lists of detected and suppressed errors, rerun with: -s
==2155== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)