简体   繁体   中英

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?

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.

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM