Memory Management
This section introduces basic memory management functions which will prove useful in solving the extra assignments.
What does it do?
Dynamically allocates memory of a certain size on the heap. The allocated memory is uninitialized.
Linux man page:
man malloc
.
Signature
The first argument (size) represents the size of the memory segment to allocate, in bytes.
Analogy
Imagine you are a librarian; you have just received a packet of a known number of books and you have available a number of shelves in your library. You need to find an empty space on a shelf where you can store all your books. The books are new and more resistant to dust particles, so you do not need a clean shelf. Once you find such an empty space, place the books there. If no space was found, then you donate them.
Similarly, you give malloc
a certain size that you need for your program (the number of books) and malloc
will try to find in your memory a segment (empty space on a shelf) big enough to fit the requested size. If it finds one, malloc will return a pointer to the start address of the allocated memory (in the library example this would be the shelf number) which you can use to access that memory block. If it does not find one, malloc will return NULL
(the packet was not placed on a shelf).
Last updated