domlao
domlao

Reputation: 16029

Use mmap to allocate memory

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?

Upvotes: 6

Views: 1790

Answers (2)

Benoit Thiery
Benoit Thiery

Reputation: 6387

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)?

Upvotes: 1

janneb
janneb

Reputation: 37238

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.

Upvotes: 6

Related Questions