Why does gcc create different assembly code for the following functions to zero out a struct?
typedef struct {
char a;
int b;
} A;
void f(A *x) {
memset(x, 0, sizeof(*x));
}
void g(A *x) {
x->a = 0;
x->b = 0;
}
void h(A *x) {
*x = (A) {0};
}
Assembly (-Ofast):
f:
mov QWORD PTR [rdi], 0
ret
g:
mov BYTE PTR [rdi], 0
mov DWORD PTR [rdi+4], 0
ret
h:
mov QWORD PTR [rdi], 0
ret
I assume it's because of padding of the data structure, but is gcc not allowed to override padding bytes, because they must not used anyway? I actually would expect that f, g and h produce identical code.
Thanks