News for hackers. Stuff that matters.
Re:Legitimate Use of Variable Length Arrays by gnode on Monday October 28, 2019 @10:43AM (#21377423)
They're trying to allocate an n·n element array. If int and size_t are 32b (typical 32-bit architectures), and n == INT_MAX, then n·n·sizeof(float) can't be represented by a size_t.

(Used · for multiplication, because HN turns stars into emphasis.)

Re:Legitimate Use of Variable Length Arrays by crististm on Monday October 28, 2019 @05:34PM (#21381959)
That may be true but an array of n x n chars where n is 2^32 won't fit (well obviously) in RAM and size_t should be at least 64 bit to match (2^32 x 2^32 = 2^64).

Regardless, even without these unobtainium big machines, the cardinality of the largest array for a platform (by any number of dimensions) must be representable in size_t. A too large of an array would not fit in RAM and you should get a compile/link/out of memory error.

Re:Legitimate Use of Variable Length Arrays by gnode on Tuesday October 29, 2019 @11:10AM (#21388021)
> A too large of an array would not fit in RAM and you should get a compile/link/out of memory error.

Except we're talking about variable sized arrays, where the wanted size is not known until runtime (e.g. from user input). We can't check this at compile time.

This also isn't the same problem as an out of memory error; we need to check that nn didn't overflow the size of size_t, as well as that the memory allocation is successful. Something like:

    int n = /* run-time value */
    size_t sz = (size_t)n;
    // Check n fits in size_t.
    if ((int)sz != n) <error>
    sz *= sz * sizeof(float);
    // Check against overflow.
    if (((sz / (size_t)n) / sizeof(float)) != (size_t)n) <error>
    float *matrix = malloc(sz);
    // Check allocation succeeded.
    if (matrix == NULL) <error>
Re:Legitimate Use of Variable Length Arrays by crististm on Tuesday November 05, 2019 @08:08AM (#21451986)
One is still confined by the limitations of the target machine. Ignoring them is at one's own peril.