Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are alternatives to malloc() in C?

Tags:

c

malloc

embedded

I am writing C for an MPC 555 board and need to figure out how to allocate dynamic memory without using malloc.

like image 260
patrick Avatar asked Feb 10 '10 23:02

patrick


Video Answer


3 Answers

Typically malloc() is implemented on Unix using sbrk() or mmap(). (If you use the latter, you want to use the MAP_ANON flag.)

If you're targetting Windows, VirtualAlloc may help. (More or less functionally equivalent to anonymous mmap().)

Update: Didn't realize you weren't running under a full OS, I somehow got the impression instead that this might be a homework assignment running on top of a Unix system or something...

If you are doing embedded work and you don't have a malloc(), I think you should find some memory range that it's OK for you to write on, and write your own malloc(). Or take someone else's.

Pretty much the standard one that everybody borrows from was written by Doug Lea at SUNY Oswego. For example glibc's malloc is based on this. See: malloc.c, malloc.h.

like image 89
asveikau Avatar answered Oct 11 '22 10:10

asveikau


If your runtime doesn't support malloc, you can find an open source malloc and tweak it to manage a chunk of memory yourself.

like image 24
President James K. Polk Avatar answered Oct 11 '22 12:10

President James K. Polk


You might want to check out Ralph Hempel's Embedded Memory Manager.

like image 30
Dan Avatar answered Oct 11 '22 10:10

Dan