Search code examples
cstacksizeof

sizeof a really big array


Why does this code

#include <stdio.h>

int main(void) {
    char big_array[10000000000];
    printf("%d", sizeof(big_array));
    return 0;
}

print the output as

1410065408

instead of 10000000000 ?

If the reason is due to the stack memory not being big enough, at what point does it give runtime error instead of allocating smaller memory?


Solution

  • Turn on warnings! You should have gotten a warning that %d doesn't match the size_t argument you gave it. The format should be "%zu\n". The 1410065408 you're getting is 10000000000 modulo 232, i.e. truncated to 32 bits.

    If you actually tried to use that array, it would likely crash. (As it is, the compiler is optimizing away the unused array.) That is way too much to allocate on the stack. You need to use malloc() for something that big.