2011-08-08 26 views
5

He asignado código usando mmap, pero no puedo liberarlo debido a un error de segmentación. He hecho mprotect - PROT_WRITE para que se pueda escribir, pero aún no puedo liberarlo.¿Cómo liberar memoria asignada usando mmap?

Por favor, ayúdame.

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

use munmap function its syntex es "int munmap (void * addr, size_t len);" –

+0

Gracias, sí, tengo uso y está funcionando :) – kingsmasher1

Respuesta

14

Necesita usar munmap para eso. No es necesario que haga nada más (cambie los bits de protección, etc.). Pero debe verificar el código de retorno de munmap.

munmap(allocation, 5000); 

free(3) sólo se puede utilizar para liberar la memoria asignada a través de malloc(3).

+0

Si uso munmap, las últimas 2 líneas, mprotect - PROT_WRITE tampoco es necesario, ¿no? Quiero decir, ¿se puede munmap hacerse en la memoria protegida? – kingsmasher1

+0

@ kingsmasher1 Seguro que puedes. – cnicutar

+0

Muchas gracias. – kingsmasher1