malloc
is a library function in C that allows for dynamic memory allocation
from the heap
. It is used to allocate a single large block of memory with the specified size and returns a pointer to the first byte in the allocated memory
. The syntax for malloc
in C is:
c
ptr = (cast-type*) malloc(byte-size)
For example, to allocate 100 integers, you would use the following code:
c
ptr = (int*) malloc(100 * sizeof(int));
Since the size of an 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
. If the space is insufficient, the allocation fails and returns a NULL
pointer
. Dynamic memory allocation is useful when you don't know the amount of memory needed during compile time
. It allows objects to exist beyond the scope of the current block, and C passes by value instead of reference, making it more efficient to assign memory and pass the pointer to another function
. To free memory allocated using malloc
, you can use the free
function:
c
free(arrayPtr);
This statement will deallocate the memory previously allocated
. It is essential to free memory to avoid memory leaks, as C does not have a garbage collector like some other languages, such as Java