Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

When to check the return from malloc function?


Asked by Aurelia Leal on Dec 07, 2021 FAQ



Always check the return from malloc, even if the amount of memory requested is small. The malloc function allocates a memory block of at least size bytes. The block may be larger than * size`* bytes because of the space that's required for alignment and maintenance information.
And,
If there is not enough memory available, the malloc function will return a NULL. If the request is granted a block of memory is allocated (reserved). The address of the reserved block will be placed into the pointer variable. The if statement then checks for the return value of NULL.
Accordingly, The C library function void *malloc (size_t size) allocates the requested memory and returns a pointer to it. Following is the declaration for malloc () function. size − This is the size of the memory block, in bytes. This function returns a pointer to the allocated memory, or NULL if the request fails.
Indeed,
The malloc function will request a block of memory from the heap. If the request is granted, the operating system will reserve the requested amount of memory. When the amount of memory is not needed anymore, you must return it to the operating system by calling the function free. Take a look at the following example:
Next,
If size is 0, malloc allocates a zero-length item in the heap and returns a valid pointer to that item. Always check the return from malloc, even if the amount of memory requested is small.