How to allocate dynamic memory using our own function (without using malloc)

how to allocate dynamic memory using our own function

without using malloc () how to allocate dynamic memory using C.

-6
source share
3 answers

If you do not want to use malloc () provided by the library, you will have to implement your own memory manager, but I see no reason for this. This code has been thoroughly tested and used for a long time. You can implement your own sample memory manager based on the sbrk () system call. I would recommend you go to the following link.

Assuming you are on Linux, check out the link below:

http://www.ibm.com/developerworks/linux/library/l-memory/

+2
source

You cannot get new heap memory without any support from the underlying operating system. I assume you have a POSIX operating system, for example. Linux

You can define your own malloc , but (in the hosted C implementation) most library functions assume that it has traditional semantics (two consecutive and successful calls to malloc without any free -s producing two unaliased pointers to separate non-overlapping memory areas).

In practice, your malloc system is usually implemented by requesting fresh segments - in multiples of 4 kilobytes of pages - from virtual memory in your address space using a system call such as MMAP (2) . But your standard C malloc tries to reuse previously free -d memory zones before calling mmap , and it allocates some β€œlarge” (for example, 128 KB or 1 MB) pieces of memory using mmap and organizes them like (the details are complicated, because the details are complicated, as most malloc implementations are optimized for real common use cases). Quite often, malloc processes small secretions other than large ones. Sometimes (but more often), the malloc implementation can free up kernel memory, for example, munmap , but in practice this happens infrequently. Thus, in practice, a process that has malloc is a lot of memory in many small zones and has free -d, almost all of them still save a lot of memory (in order to be able to reuse it without any mmap ),

+2
source

There is no reason not to use malloc to dynamically allocate memory.

However, you can define a global char array with a very large size and write a series of functions to transfer space from this array. However, you need to track what is / is not available and be aware of alignment issues. And it just scratches the surface.

Bottom line: use malloc .

0
source

All Articles