C malloc()
Published Aug 18, 2022
The malloc() function is used to allocate a block of memory in the heap. It allocates the user a specified number of bytes but does not initialize. Once allocated, the program accesses this block of memory via a pointer that malloc() returns.
Syntax
malloc(size);
The size parameter is of type size_t.
The default pointer returned by malloc() is of the type void but can be cast into a pointer of any data type. However, if the space is insufficient for the amount of memory requested by malloc(), then the allocation fails and a NULL pointer is returned.
Example
The following example showcases the malloc() function:
int *ptr;// The pointer ptr holds the address of the first byte in the allocated memoryptr = (int*) malloc(5 * sizeof(int));
Since the size of int is 4 bytes, the above statement will allocate 20 bytes (4 * 5) of memory.
Learn C on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours