Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to free memory allocated using mmap?

Tags:

c

linux

memory

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. My code:

 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 
like image 607
RajSanpui Avatar asked Aug 08 '11 09:08

RajSanpui


People also ask

Does mmap allocate memory?

The mmap() system call can also be used to allocate memory (an anonymous mapping). A key point here is that the mapped pages are not actually brought into physical memory until they are referenced; thus mmap() can be used to implement lazy loading of pages into memory (demand paging).

How do I free up memory on malloc?

When you no longer need a block that you got with malloc , use the function free to make the block available to be allocated again. The prototype for this function is in stdlib. h .

Does exit free allocated memory?

When you exit the program, all allocated memory is reclaimed by the OS (both the stack and the heap). Your program doesn't leave any footprint in the RAM, unless you work outside the program's memory through buffer overflows and such.

Is mmap shared memory?

Using mmap on files can significantly reduce memory overhead for applications accessing the same file; they can share the memory area the file encompasses, instead of loading the file for each application that wants access to it. This means that mmap(2) is sometimes used for Interprocess Communication (IPC).


1 Answers

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

munmap(allocation, 5000);

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

like image 175
cnicutar Avatar answered Sep 28 '22 02:09

cnicutar