Search code examples
cmacrosstdint

Maximum size of object macro


I tried to write the following:

#include <stdint.h>
#include <stdlib.h>

void *ptr = malloc(SIZE_MAX);

But the compiler gave me the following warning:

warning: argument 1 value ‘18446744073709551615’ exceeds maximum object 
size 9223372036854775807 [-Walloc-size-larger-than=]

That sounds reasonable. But anyway I'd like to allocate an object of the max possible size on the current implementation/arch. There is the macro RSIZE_MAX defined in the Annex.B(19):

__STDC_WANT_LIB_EXT1__
RSIZE_MAX

So I tried the following example:

#define __STDC_WANT_LIB_EXT1__
#include <stdint.h>
#include <stdlib.h>

int main(){
    void *ptr = malloc(RSIZE_MAX);
}

But with no effect, the RSIZE_MAX is not defined. How to use this macro or any other way to verify maximum object size at compile time?


Solution

  • RSIZE_MAX is defined in C11 Annex K, which is optional. An implementation that supports it will predefine the macro __STDC_LIB_EXT1__. The gcc/glibc implementation I use on my Ubuntu system, for example, does not support it, and therefore does not define RSIZE_MAX.

    In any case, there's no guarantee that malloc(RSIZE_MAX) will succeed, nor is there any implication in the standard that RSIZE_MAX, even if it's defined, is the maximum allocation size supported by malloc. Evaluating malloc(RSIZE_MAX+1) isn't even a runtime-constraint violation; malloc() still takes an argument of type size_t, not rsize_t. malloc reports failure by returning a null pointer.

    See N1570 K.3.4:

    The macro is

    RSIZE_MAX

    which expands to a value of type size_t. Functions that have parameters of type rsize_t consider it a runtime-constraint violation if the values of those parameters are greater than RSIZE_MAX.

    Note that on some systems (particularly Linux-based systems), malloc() can appear to succeed, returning a non-null result, even if there isn't enough memory available for the allocation. See "overcommit" and "OOM killer".