0

I wonder what is the maximal array size in C, weither it depends on the type of data, and if it depends where it is declared (heap or stack).

The following code works with int up to a size of 1048576 (2^20), also 1048577 (same + 1), but not with 2097152 (2^21) - I have not searched for the precise limit:

#include <stdio.h>

#define MAX 1048577llu /* 2097152llu */

int main()
{
    int tab[MAX];
    /* long long int tab[MAX] */
    tab[MAX - 1] = 123;
    printf("tab[%llu] declared, tab[%llu] = %d\n", MAX, MAX - 1, tab[MAX - 1]); 
    return 0;
}

With long long int, it fails at 2^20, but succeeds at 2^19.

lalebarde
  • 1,684
  • 1
  • 21
  • 36
  • 2
    Frequently asked: local variables are usually placed on the stack, which has limited capacity. – Weather Vane May 21 '18 at 18:10
  • However much space your stack has probably. (It will vary between compilers and architectures.) – Rivasa May 21 '18 at 18:12
  • Terrible duplicate. This is as much as to do with a theoretical limit; and I couldn’t see a good fit for that. – Bathsheba May 21 '18 at 18:16
  • 1
    There are some other relevant questions: https://stackoverflow.com/questions/14753036/what-maximum-size-of-static-arrays-are-allowed-in-c https://stackoverflow.com/questions/11698811/is-there-any-limitation-of-array-length-in-c https://stackoverflow.com/questions/216259/is-there-a-max-array-length-limit-in-c (note last one is actually C++) that should help – Dietrich Epp May 21 '18 at 18:16
  • @Bathsheba then rewind it. The question is about local variable storage, not theoretical limits. – Weather Vane May 21 '18 at 18:16
  • @WeatherVane: that’s a crying shame. Think I’ll hang my tools up for the day! – Bathsheba May 21 '18 at 18:18
  • And the new duplicate has an answer superior to mine. – Bathsheba May 21 '18 at 18:19
  • @Bathsheba soneone else did it, but the question does ask if it depends where the array is stored. – Weather Vane May 21 '18 at 18:19
  • 1
    @Bathsheba: Not trying to step on any toes here. I couldn't find an exact duplicate, but the subject roughly divides into questions about stack limits, heap limits, and implementation limits. – Dietrich Epp May 21 '18 at 18:19

0 Answers0