0

Lets say we perform

malloc(4 * sizeof(int))

Now, the number 4 is a constant and from my understanding sizeof is actually compile time function (unless you have a variable inside of it).

In this case (considering x86) sizeof(int) would also be 4. My question is: will the gcc optimization perform the calculation itself or will the equation be generated in the asm?

YSC
  • 38,212
  • 9
  • 96
  • 149

1 Answers1

4

This is called "constant-folding" and yes, it will happen before assembly. Assembly in itself is usually not optimized at all.

Consider the minimal program

#include <stdlib.h>

int main(void)
{
    malloc(4 * sizeof(int));
}

We can compile it into assembly with gcc -S. On my computer, the resulting assembly says:

main:
        pushq   %rbp
        movq    %rsp, %rbp
        movl    $16, %edi
        call    malloc@PLT
        movl    $0, %eax
        popq    %rbp
        ret

I.e. the only constants you see in there are 16 (4 * sizeof(int)), and 0 (the implicit return value from main()).


Note that in C there is a class of expressions that are called "integer constant expressions" that are supposed to be evaluated at the compilation time. You can use 4 * sizeof(int) as the size of an array - or even within a _Static_assert clause - naturally then it must be evaluated during the compilation, but in general case, such as here, the C standard does not require one or the other.