Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple c malloc

Tags:

c

malloc

realloc

While there are lots of different sophisticated implementations of malloc / free for C/C++, I'm looking for a really simple and (especially) small one that works on a fixed-size buffer and supports realloc. Thread-safety etc. are not needed and my objects are small and do not vary much in size. Is there any implementation that you could recommend?

EDIT:

I'll use that implementation for a communication buffer at the receiver to transport objects with variable size (unknown to the receiver). The allocated objects won't live long, but there are possibly several objects used at the same time.

As everyone seems to recommend the standard malloc, I should perhaps reformulate my question. What I need is the "simplest" implementation of malloc on top of a buffer that I can start to optimize for my own needs. Perhaps the original question was unclear because I'm not looking for an optimized malloc, only for a simple one. I don't want to start with a glibc-malloc and extend it, but with a light-weight one.

like image 527
Thomas Avatar asked Sep 20 '10 14:09

Thomas


People also ask

What is malloc in C with example?

ptr = (cast-type*) malloc(byte-size) For Example: ptr = (int*) malloc(100 * sizeof(int)); Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory.

What is malloc function in C?

What is malloc() in C? malloc() is a library function that allows C to allocate memory dynamically from the heap. The heap is an area of memory where something is stored. malloc() is part of stdlib. h and to be able to use it you need to use #include <stdlib.

Does C have malloc?

Memory allocation (malloc), is an in-built function in C. This function is used to assign a specified amount of memory for an array to be created. It also returns a pointer to the space allocated in memory using this function.

What does malloc () calloc () realloc () free () do?

Functions malloc, calloc, realloc and free are used to allocate /deallocate memory on heap in C/C++ language. These functions should be used with great caution to avoid memory leaks and dangling pointers.


2 Answers

Kerninghan & Ritchie seem to have provided a small malloc / free in their C book - that's exactly what I was looking for (reimplementation found here). I'll only add a simple realloc.

I'd still be glad about suggestions for other implementations that are as simple and concise as this one (for example, using doubly-linked lists).

like image 153
Thomas Avatar answered Nov 10 '22 09:11

Thomas


I recommend the one that came with standard library bundled with your compiler.

One should also note there is no legal way to redefine malloc/free

like image 35
Martin York Avatar answered Nov 10 '22 09:11

Martin York