How much memory calloc and malloc can allocate?
Solution 1
Aside from being limited by the amount RAM in the PC, it is system dependent, but on Windows, it's _HEAP_MAXREQ
according to the MSDN article on malloc
. Note though malloc
and calloc
are not guaranteed to allocate anything. It all depends on how much memory is available on the executing PC.
malloc sets errno to ENOMEM if a memory allocation fails or if the amount of memory requested exceeds _HEAP_MAXREQ.
_HEAP_MAXREQ
is defined as follows in malloc.h
(at least in the Visual Studio 2010 includes).
#ifdef _WIN64
#define _HEAP_MAXREQ 0xFFFFFFFFFFFFFFE0
#else
#define _HEAP_MAXREQ 0xFFFFFFE0
#endif
You shouldn't really worry about this though. When using malloc
you should decide how much memory you really need, and call it with that as the request. If the system cannot provide it, malloc
will return NULL
. After you make your call to malloc
you should always check to see that it's not NULL
. Here is the C example from the MSDN article on proper usage. Also note that once you've finished with the memory, you need to call free
.
#include <stdlib.h> // For _MAX_PATH definition
#include <stdio.h>
#include <malloc.h>
int main( void )
{
char *string;
// Allocate space for a path name
string = malloc( _MAX_PATH );
// In a C++ file, explicitly cast malloc's return. For example,
// string = (char *)malloc( _MAX_PATH );
if( string == NULL )
printf( "Insufficient memory available\n" );
else
{
printf( "Memory space allocated for path name\n" );
free( string );
printf( "Memory freed\n" );
}
}
Solution 2
You can allocate as much bytes as type size_t
has different values. So in 32-bit application it is 4GB in 64-bit 16 I don't even know how to call that size
All in all you can allocate all memory of machine.
Solution 3
As far as the language definition is concerned, the only upper limit per call is what size_t
will support (e.g., if the max size_t
value is 232-1, then that's the largest number of bytes malloc
can allocate for a single block).
Whether you have the resources available for such a call to succeed depends on the implementation and the underyling system.
Vijay Chauhan
Just love to develop softwares. I am interested in developing web based applications,websites,and maintaining database.
Updated on June 04, 2022Comments
-
Vijay Chauhan almost 2 years
How much memory
calloc
andmalloc
can allocate?As
malloc
andcalloc
can allocate memory dynamicallyExample
void *malloc (size_in_bytes);
And
calloc
can allocate memory depending on the number of blocksExample
void *calloc (number_of_blocks, size_of_each_block_in_bytes);