Reputation: 2909
On a 64 bit linux machine I wrote the following small C program:
#include <stdlib.h>
#include <stdio.h>
int main (void)
{
#define BLOCK_SIZE (1024*1024)
int i;
for (i = 1; ; i++)
{
char *p = (char *)malloc(i * BLOCK_SIZE);
if (p == 0)
break;
*p = 13;
free(p);
}
printf ("Allocated max %d MB\n", (i - 1));
return 0;
}
If I compile this with -O0 -m64
, I can allocate 2047 MB on my desktop system. If I compile the same program with -O0 -m32
3829 MB.
Why is the maximal malloc size for a 32 bit binary larger than for a 64 bit binary on the same machine?
Edit: If I activate the optimizer with -O3
, the maximal amount of memory is 20588 on a 64 bit machine.
Upvotes: 1
Views: 1636
Reputation: 612794
You are trying to store a number greater than 2^31 in a signed 32 bit int
. It does not fit. Use size_t
instead for the size that you pass to malloc
. Change the type of i
to size_t
.
Upvotes: 10