Sam Welch
Sam Welch

Reputation: 53

Dynamically Allocate Memory without Malloc

I've been given a task to dynamically manage memory to beat the speed of malloc. Some requirements:

1) Have a pointer to a struct

2) Use "Chunks" of memory

3) The memory will be allocated with a call like

init(memory * mem, int chunk_size, int num_chunks)

4) The memory pointer will be declared globally.

5) Not using system calls

So, I've thought about having my struct simply just:

typdef struct {
  char *byte;
} memory;

And then that would leave my init function to do something like:

mem = new memory[chunk_size * num_chunks];

I don't know if you can do that in C -- normally I would use malloc! And then to free would I be able to just be able to set the pointer to null?

Thanks for the help!

Upvotes: 5

Views: 21390

Answers (2)

aks
aks

Reputation: 167

You can implement your own version of 'malloc' using system calls for process memory management... Try brk, sbrk and mmap system calls to get memory from kernel...

This has a easy to understand implementation which you can implement and improve on

http://www.inf.udec.cl/~leo/Malloc_tutorial.pdf

Upvotes: 7

user25581
user25581

Reputation:

No, new is not supported in C, and setting a pointer to null does not free the associated memory. In fact that's a good way to leak memory.

It depends on the details of what you are trying to do, but typically you'd make some initial call to malloc() to get a largish block of memory, and then write your custom functions which you'd use to manage allocations from that large block within your program.

If you don't want to use malloc() at all, you'll have to use one of the memory allocation calls for your operating system. For example under Windows you might call HeapAlloc() or GlobalAlloc(). on UNIX systems you'd call brk() or sbrk().

Upvotes: 1

Related Questions