0

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?

St.Antario
  • 26,175
  • 41
  • 130
  • 318

2 Answers2

3

The define SIZE_MAX defines the maximum value of the data type size_t. The data type size_t is capable to store the size of any object. The maximum size depends on the bus with like 32 or 64 bit.

If you try to allocated memory of the the maximum countable size of memory, it must fail, since this would block your entire address space. The compiler gives you a warning that the malloc call will always fail. The requested size just makes no sense.

BTW: 9223372036854775807 is 0x7FFFFFFFFFFFFFFF

harper
  • 13,345
  • 8
  • 56
  • 105
1

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".

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631