Malloc Function
In C -- a programming language designed by Dennis Ritchie at AT&T Bell Laboratories in the early 1970s -- the malloc function is a means of allocating memory dynamically, or in response to demand, rather than in absolute terms. Sometimes programmers don't know how much memory will be needed for data at the time they are writing a program, so malloc allows them to allocate memory dynamically after the program has started running.
-
Memory Allocation
-
By default, the malloc function allocates a contiguous, or adjacent, block of memory on an area known as a heap, which can be accessed by a program to store data and variables. The malloc function takes a single argument, a long or 32-bit integer that represents the number of bytes to allocate from the heap. The malloc function asks the system for a block of memory of the size specified and returns a pointer -- an address, from the point of view of the programming language -- to the first element of the block.
Return Value
-
Computers only have a finite amount of memory, so it is possible for the malloc function to request more memory than is physically available and cause a program to crash. If not enough memory is available, malloc returns a null pointer, or a pointer with a value of zero. To prevent a program from crashing, programmers must explicitly test that malloc hasn’t returned null, so that they know that the requested memory was allocated successfully before attempting to use it.
-
Releasing Memory
-
Similarly, a computer cannot perpetually allocate more and more memory -- and repeatedly overwriting a pointer that points to dynamically-allocated memory can lead to data becoming inaccessible. Dynamically-allocated memory must therefore be released back to the system memory pool, using the free function, once it is no longer needed. Once a process terminates, all the dynamically-allocated memory is released back to the memory pool.
Syntax
-
Malloc returns a generic pointer, or a pointer to void, but the pointer may be typed, or typecast, to indicate the type of data to which it points. The syntax "char *str = (char *) malloc(40)," for example, allocates memory for a string 40 characters long. Alternatively, programmers can declare a pointer and invoke malloc when they wish to make space for the elements in an array. However, it is important to note that the malloc function only allocates memory. It does not empty or otherwise initialize the memory it allocates.
-
References
- Photo Credit Comstock/Comstock/Getty Images