2011-08-08 27 views
5

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

请帮帮我。

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 
+0

使用munmap函数它的syntex是“int munmap(void * addr,size_t len);” –

+0

谢谢,是的,我有使用,它的工作:) – kingsmasher1

回答

14

您需要使用munmap。你不需要做任何事情(改变保护位等)。但你应该检查munmap的返回码。

munmap(allocation, 5000); 

free(3)只能用于经由malloc(3)分配的内存。

+0

如果我使用munmap,最后2行,mprotect - PROT_WRITE也不需要,对吧?我的意思是可以在受保护的内存上完成munmap吗? – kingsmasher1

+0

@ kingsmasher1当然可以。 – cnicutar

+0

非常感谢。 – kingsmasher1