Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use mmap to allocate memory

Tags:

c

posix

mmap

I need to allocate memory but I can't use malloc because its not reentrant, so basically I will implement dynamic memory allocation using POSIX mmap function. Is it possible to use mmap?

like image 419
domlao Avatar asked Jan 20 '11 10:01

domlao


2 Answers

Yes, mmap() should be reentrant so you should be able to use that. Note that mmap() is often a quite slow operation so you're probably better of using it only in those (hopefully) few and far between cases where it's really needed, rather than as a general purpose malloc() replacement.

POSIX 2008 contains a list of async-signal-safe functions that are safe to call from a signal handler function (see the table in section 2.4.2 in the link). mmap() is not in that list, that is, calling mmap() from a signal handling function may result in undefined behavior.

What you can do is to avoid allocating memory in signal handlers, just set some flag and do the actual work later.

like image 150
janneb Avatar answered Sep 28 '22 16:09

janneb


EDIT: replaced reentrant by thread-safe

malloc is thread-safe on most OS.

Which one are you using and are you sure it is not thread-safe? Or do you need it to be reentrant (I guess not)?

like image 24
Benoit Thiery Avatar answered Sep 28 '22 14:09

Benoit Thiery