In: Computer Science
malloc() searches the recently de-allocated memory objects to satisfy incoming memory allocation request. Explain the rationale of this design.
The procedure in which the size of a data structure is changed during the runtime is called C Dynamic Memory Allocation.
Some functions are provided by C are to achieve these tasks. Under <stdlib.h> header there are library functions provided by C defined file to facilitate dynamic memory allocation in C programming. One of the library is:
malloc()
It is also referred to as “memory allocation” method in C. It is used to dynamically allocate a single large block of memory with the specified size. A pointer of type void is returned. It initializes each block with default garbage value.
Syntax:
ptr = (cast-type*) malloc(byte-size)
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.
Rationale behind the design:
We need to call malloc to get memory at
runtime. malloc is used to allocate a block of memory on
the heap. The program accesses this block of memory via a pointer
that malloc returns. When the memory is no longer needed, the
pointer is passed to free
which
deallocates the memory so that it can be used for other
purposes.
Local arrays are allocated on the stack, which is a small pre-allocated memory for your program. Beyond a couple thousand data, you can't really do much on a stack. For higher amounts of data, you need to allocate memory out of your stack.
This is what malloc does. It allocates a piece of memory as big as you ask it. It returns a pointer to the start of that memory, which could be treated similar to an array.