Blue
Blue

Reputation: 19

Cast void pointer to “type” variable or use memcpy?

I haven’t been able to find an answer for this. Does it matter which of these methods I use in C?

int get_int(void *vptr) {
    return *(int *)vptr;
}

or

int get_int(void *vptr) {
    int i = 0;
    memcpy(&i, vptr, sizeof(int));
    return i;
}

It seems to give the same result on my tests but is this equivalent in every case?

Upvotes: 1

Views: 282

Answers (3)

chux
chux

Reputation: 154174

but is this equivalent in every case?

No.

*(int *)vptr relies on int alignment. If vptr does not point to int alsigned data, the result is UB.

memcpy() does not have than requirement. It "works" as long as the data is not some trap (rare).

Upvotes: 0

Chris Dodd
Chris Dodd

Reputation: 126448

The main difference is that the memcpy will work in more cases -- it just requires that the memory being copied from contains data of the appropriate type. The cast-and-dereference requires that and also requires that the pointer is valid for accessing that type. On most machines, this (just) requires proper alignment. The cast also allows the compiler to assume that it does not alias with a value of a different type.

The net result is that the memcpy is perhaps "safer", but also perhaps a bit more expensive.

Upvotes: 2

Dúthomhas
Dúthomhas

Reputation: 10093

No, it is not equivalent because, believe it or not, not all pointers are the same in all cases (though on x86+ architectures they are).

The cast, however, will work where it is defined.

Upvotes: -1

Related Questions