Linux 如何释放使用 mmap 分配的内存?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6979892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 05:33:37  来源:igfitidea点击:

How to free memory allocated using mmap?

clinuxmemory

提问by kingsmasher1

I have allocated code using mmap, but unable to free it because of segmentation fault. I have done mprotect - PROT_WRITE to make it writable, but still i am unable to free it.

我已经使用 mmap 分配了代码,但由于分段错误而无法释放它。我已经完成了 mprotect - PROT_WRITE 使其可写,但我仍然无法释放它。

Please help me.

请帮我。

enter code here
 1 #include <stdio.h>
 2 #include <memory.h>
 3 #include <stdlib.h>
 4 #include <unistd.h>
 5 #include <sys/mman.h>
 6 #include <sys/types.h>
 7 #include <fcntl.h>
 8 
 9 int main()
10 {
11  void * allocation;
12  size_t size;
13  static int devZerofd = -1;
14 
15  if ( devZerofd == -1 ) {
16                 devZerofd = open("/dev/zero", O_RDWR);
17                 if ( devZerofd < 0 )
18                         perror("open() on /dev/zero failed");
19 }
20 
21  allocation = (caddr_t) mmap(0, 5000, PROT_READ|PROT_NONE, MAP_PRIVATE, devZerofd,  0);
22 
23  if ( allocation == (caddr_t)-1 )
24                 fprintf(stderr, "mmap() failed ");
25 
26  if ( mprotect((caddr_t)allocation, 5000, PROT_WRITE) < 0 )
27         fprintf(stderr, "mprotect failed");
28  else
29         printf("mprotect done: memory allocated at address %u\n",allocation);
30 
31  strcpy(allocation,"Hello, how are you");
32  puts(allocation);
33 
34  if ( mprotect((caddr_t)allocation, 5000, PROT_WRITE) < 0 )
35         fprintf(stderr, "mprotect failed");
36 
37  free(allocation);
38 
39 }
40 
41 

采纳答案by cnicutar

You need to use munmapfor that. You don't need to do anything else (change protection bits etc). But you should check the return code of munmap.

你需要使用munmap它。您不需要做任何其他事情(更改保护位等)。但是您应该检查munmap.

munmap(allocation, 5000);

free(3)can only be used to free memory allocated via malloc(3).

free(3)只能用于释放通过malloc(3).