Kevin Meier
Kevin Meier

Reputation: 2582

GCC: Zeroing a struct

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

Upvotes: 4

Views: 136

Answers (1)

Neal Burns
Neal Burns

Reputation: 849

In the case of f, you are implicitly casting to void*, so memset() shouldn't make assumptions about what is pointed to by x.

void * memset ( void * ptr, int value, size_t num );

Upvotes: 1

Related Questions