I want to determine what is the maximum limit of memory I can allocate in my computer. This is the code that I have written for this task:
#include <stdio.h>
#include <stdlib.h>
int main() {
int j;
int *primes;
int i ;
int limit = 2147483647;
primes = malloc(sizeof(int) * limit);
for (i = 0; i < limit; i++)
{
primes[i] = 1;
}
return 0;
}
How can I determine how much memory can be allocated without hit and trial? I have allocated the maximum int size in this example. But the program crashes. How much memory is really being allocated in this example?
malloc()
is allowed to fail, in which case it returns a NULL-pointer without allocating any memory. It is always an all-or-nothing allocation. It either succeeds and allocates a full chunk of memory of the requested size, or it fails, returning a NULL-pointer without allocating a single byte.
As for knowing how much memory is available - that really depends on the environment: what OS are you running this in, is that a 16-, 32-, 64-bit memory architecture?
For instance, if you are running on Windows 10 you can use the GlobalMemoryStatusEx()
facility (refer to MSDN:GlobalMemoryStatusEx() for details).
Linux, OTOH, provides a neat sysconf()
way of retreiving similar information. Refer to this page for more details.
Even if your OS is 64-bit that wouldn't necessarily mean that your application can access more than a certain limit. For instance Windows 7 64-bit will only let you address up to 8GB of memory in your application code even though the full virtual memory space is 16TB.
You code is wrong for so many reasons like
You're assuming that malloc()
offers partial allocation (up to the available memory) which is again, wrong.
Quoting the C11
standard, chapter §7.22.3.4, (emphasis mine)
The
malloc
function returns either a null pointer or a pointer to the allocated space.
So, it's either complete success (with the exact amount of requested memory allocated) or complete failure (return of null pointer), there's no trade-off like partial success with available memory or whatever which you might have assumed.
You're not checking for malloc()
success, resulting probable null-pointer dereference.
I believe, you're in need of getrlimit()
and family to achieve your purpose. Particular point of interest would be RLIMIT_DATA
as the resource
value.
That said,
1. "I have allocated the maximum int size in this example"
This does not seem to be connected with the limits for malloc()
and family, anyways.
2. "But the program crashes"
That is most probably the result of undefined behavior. In your code, you directly dereference the returned pointer, without success check for malloc()
. It is likely that malloc()
has failed and returned a NULL
, dereferencing that causes the UB.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With