Explain the use of malloc function in C programming.
Explain the use of malloc function in C programming?
C malloc() method
“malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It initializes each block with a default garbage value.
Syntax:
ptr = (cast-type*) malloc(byte-size)
For 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.
Description
The C library function void *malloc(size_t size) allocates the requested memory and returns a pointer to it.
Declaration
Following is the declaration for malloc() function.
void *malloc(size_t size)
Return Value
This function returns a pointer to the allocated memory, or NULL if the request fails
If space is insufficient, allocation fails and returns a NULL pointer.
Example:
Enter number of elements: 5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5
Comments
Post a Comment