Home > Software design >  Cast void pointer to “type” variable or use memcpy?
Cast void pointer to “type” variable or use memcpy?

Time:10-24

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?

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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

  • Related