arrayscsizeof

How does "sizeof" determine the size of an array?


How does C find the size of an array at runtime? Where is the information about the array size or bounds stored ?


Solution

  • sizeof(array) is implemented entirely by the C compiler. By the time the program gets linked, what looks like a sizeof() call to you has been converted into a constant.

    Example: when you compile this C code:

    #include <stdlib.h>
    #include <stdio.h>
    int main(int argc, char** argv) {
        int a[33];
        printf("%d\n", sizeof(a));
    }
    

    you get

        .file   "sz.c"
        .section        .rodata
    .LC0:
        .string "%d\n"
        .text
    .globl main
        .type   main, @function
    main:
        leal    4(%esp), %ecx
        andl    $-16, %esp
        pushl   -4(%ecx)
        pushl   %ebp
        movl    %esp, %ebp
        pushl   %ecx
        subl    $164, %esp
        movl    $132, 4(%esp)
        movl    $.LC0, (%esp)
        call    printf
        addl    $164, %esp
        popl    %ecx
        popl    %ebp
        leal    -4(%ecx), %esp
        ret
        .size   main, .-main
        .ident  "GCC: (GNU) 4.1.2 (Gentoo 4.1.2 p1.1)"
        .section        .note.GNU-stack,"",@progbits
    

    The $132 in the middle is the size of the array, 132 = 4 * 33. Notice that there's no call sizeof instruction - unlike printf, which is a real function.