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

What happens if malloc fails to allocate memory?


Asked by Scarlette Anderson on Dec 07, 2021 FAQ



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. If space is insufficient, allocation fails and returns a NULL pointer. Enter number of elements: 5 Memory successfully allocated using malloc.
In respect to this,
The “malloc” or “memory allocation” method 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.
In fact, The allocation may fail if the memory is not sufficient. In this case, it returns a NULL pointer. So, you should include code to check for a NULL pointer. Keep in mind that the allocated memory is contiguous and it can be treated as an array. We can use pointer arithmetic to access the array elements rather than using brackets [ ].
Moreover,
The malloc() function stands for memory allocation. It is a function which is used to allocate a block of memory dynamically. It reserves memory space of specified size and returns the null pointer pointing to the memory location. The pointer returned is usually of type void.
One may also ask,
4 In theory, yes. In reality, if malloc fails the operating system is probably about to crash. PS: Your second example is much harder to read than the first and should be rejected by a code review. – Steve Wellens