Maximum Index of an array and it's length on a platform

1

In C, the index of an array of char can range from 0 to 2 ^ (sizeof(size_t) * CHAR_BITS), but the count of the array's members, is that number plus 1, which can't be hold by a size_t variable.

For example, in x86, if sizeof(size_t) is 4, then the index can go from 0 to 0xFFFFFFFF, but the count of the members, if the array is full, is 0xFFFFFFFF + 1. which can't be hold by sizeof(size_t).

1) Is this correct?
2) I'm considering to limit the highest index to 0xFFFFFFFE, is there any better solution?

I know this example is extreme, but I want to use it as a reference.

c
arrays
asked on Stack Overflow Sep 1, 2017 by Bite Bytes • edited Sep 1, 2017 by Bite Bytes

2 Answers

1

The C standard says that the size of an object is returned with sizeof and its type is size_t and the return value is in bytes, so it could be pretty safe to say that for all sorts of ordinary objects, the absolute maximum size in bytes would be SIZE_MAX. One cannot allocate an object greater than SIZE_MAX with malloc, realloc; but the API of calloc could allow that.

Therefore any array has maximum of SIZE_MAX elements.

While a single object cannot exceed SIZE_MAX, the total number of bytes in all objects in a program may well exceed SIZE_MAX.

answered on Stack Overflow Sep 1, 2017 by Antti Haapala
1

Objects

The largest size of an object is about SIZE_MAX. sizeof object returns the size of any object. The type returned is type size_t. The range of size_t is [0...SIZE_MAX].

The size limit is effective one less as the address after the object needs to be computable.

Since an array is an object, the largest 4-byte int array would be

int big_int_array[SIZE_MAX/sizeof(int)];  // Perhaps 1 less

Allocations

The largest memory that be be allocated via malloc() is about SIZE_MAX.

char *big_array = malloc(SIZE_MAX - 1);

The largest memory that be be allocated via calloc() is about SIZE_MAX * SIZE_MAX bytes, yet such a large allocation attempts usually return NULL.

double *big_array = calloc(SIZE_MAX/2, sizeof *big_array);

Rare machines allows this, not Linux. Most platforms will returns NULL if the product meets/exceeds SIZE_MAX.

Here, big_array[] can be indexed [0...SIZE_MAX/2). This usually requires the address scheme to not be the traditional universal linear model many platforms employ.

answered on Stack Overflow Sep 1, 2017 by chux • edited Sep 1, 2017 by chux

User contributions licensed under CC BY-SA 3.0