Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof a really big array

Tags:

c

stack

sizeof

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?

like image 401
chiru player Avatar asked Nov 04 '25 08:11

chiru player


1 Answers

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.

like image 50
Mark Adler Avatar answered Nov 07 '25 04:11

Mark Adler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!