Is there a limit to the amount of memory that can be allocated from a program? By that I mean, is there any protection from a program, for example, that allocates memory in an infinite loop?
When would the call to malloc()
return a NULL pointer?
Is there a limit to the amount of memory that can be allocated from a program? By that I mean, is there any protection from a program, for example, that allocates memory in an infinite loop?
When would the call to malloc()
return a NULL pointer?
Yes, there is a limit. What that limit is depends on many factors, including (but not limited to):
setrlimit()
and the (obsolete) ulimit()
function).When memory cannot be allocated, malloc()
will return NULL
. If the system is completely out of memory, your process may be terminated forcefully.
From Wikipedia,
The largest possible memory block
malloc
can allocate depends on the host system, particularly the size of physical memory and the operating system implementation. Theoretically, the largest number should be the maximum value that can be held in asize_t
type, which is an implementation-dependent unsigned integer representing the size of an area of memory. The maximum value is 2CHAR_BIT × sizeof(size_t)
− 1
, or the constantSIZE_MAX
in the C99 standard.
It depends on the operating system and the standard library.
On Linux,
When you run out of address space, malloc()
will return NULL
.
When you run out of both physical memory and swap space, the OOM killer will run and kill a process to free memory.
I am tackling this issue in Reverse.
See pointer
stores addresses of memory blocks. If we able to find maximum address it can store then we can find memory allocated to our program.
Code
#include <stdio.h>
int main()
{
void *p;
printf("%zu",sizeof(p));
return 0;
}
Output
8
Understanding:
pointer size is 8 bytes.
8 bytes -> 64 bits
Max address it can store/ last memory block address: 2^64-1
Memory block addresses: 0, 1, 2, 3, ... 2^64-1
Memory allocated to program: 2^64 byte