1024 * 1024 * 1024 * 1024
most likely invokes undefined behaviour:
1024
is a int
constant. Operations are done with the "largest" type of both operands, but at least int
. Both operands are int
, so the multiplication types are int * int -> int
. The same for the following multiplications. I.e. the final result is int
. On typical systems int
is not more than 32 bits. The type of the parameter is irrelevant for the expression.
The result of the multiplication overflows an int
(unless it is more than 41 bits), which invokes undefined behaviour. Anything can happen (often, but not guaranteed: the result is truncated, yielding 0
).
To avoid this, you should use (size_t)1024 * 1024 * 1024 *1024
. This will (according to conversion rules) will perform the calculations with whichever standard type size_t
has on your system.
Beforehand use a static assertion to ensure size_t
can represent the result:
_Static_assert(SIZE_MAX >= 1024ULL * 1024 * 1024 *1024, "size_t is too small");`
Without this the multiplication would be truncated on a too small size_t
(rules are different for signed and unsigned integers!) and you end up passing 0
.
According to the standard malloc(0)
is implementation defined either NULL
or a pointer which must not be used to access an object.
Keeping all this in mind, your code might return a non-null pointer, which must not be used for accesses. But as you just test it, it is fine, but useless.