What is behind the malloc() dynamic allocation function?

Asked

Viewed 217 times

6

What mechanisms the function malloc() uses in practice to manage dynamic memory allocation in a program?

  • 2

    Link to quite complete article from IBM, in English.

  • 1

    Not quite duplicated, but this other question can be of help: http://answall.com/questions/3797/o-que-s%C3%A3o-e-onde-est%C3%A3o-o-stack-e-heap

1 answer

6


Briefly:

Your program/process occupies a memory region that goes from an address x to an address y so-called mount (heap). All of his mallocs are allocated in this area between x and y. It maintains a data structure, let’s say a list, which contains all the free spaces of the stack of this process.

When you call the malloc, it looks through this list and looks for a space that is large enough for the size you want to allocate. If it has this size available, it returns a pointer to this space, records that it will use it and from there your program will use that slice in memory.

When you desaloca calling the free(), it takes this useful space that will now be released, deregisters it and now this space released goes to the list and if any new allocation request occurs, there is space available again.

If you call malloc() and he can’t find any space large enough in the stack, he uses the syscall brk() to increase this range. That is, increase address y and relocate all old and new addresses y to be a valid memory track.

brk() is a syscall, and therefore there is no way to do the same thing in the user layer.

Look for more information about the syscall if you wish to understand the operation of syscall in itself.

  • Just watch that translation of heap would be mount, not pile. Pile is stack. I’ve already edited your answer to fix this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.