I want to allocate a 2.9GB char array with
database = (char*) malloc((2900 * 1000000 * sizeof(char)));
This gives an integer overflow warning and the malloc returns NULL. The
malloc parameter is of type size_t which according to documentation is of type
unsigned int.
So the max should be UINT_MAX which is at least 2.9GB. However, if
I try to allocate more than MAX_INT the malloc fails. Does this mean
size_t on my system is of type int? How do I check this? I looked through
/usr/include/stdlib.h
and
./lib/gcc/x86_64-redhat-linux/4.1.1/include/stddef.h
but
can’t find the definition of size_t. Thanks very much
There are two issues here.
First, the overflow warning: both
2900and1000000are of typeint, so the result of multiplying them is also of typeint. The result cannot be represented by a 32-bit signed integer, so it overflows. You need to cast one (or both) arguments tosize_tto use unsigned arithmetic.(Or, you could move the
sizeof(char)to be one of the first two terms, since its type issize_t, though you can also just remove thesizeof(char)since it is always1.)Second, the maximum size that
malloccan allocate depends both on the platform on which you are running and on the current state of the program. If there is insufficient contiguous address space left to satisfy the request, obviously themallocwill fail.Further, the platform on which you are running may have an upper limit on how large an object it can dynamically allocate. You’ll need to consult your platform’s documentation to find out what that upper limit is.
size_tis certainly notint, becauseintis always signed andsize_tis always unsigned.