Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

correct (or safest )way of initializing void pointer with non-zero value?

The following works:

void* p = reinterpret_cast<void*>(0x1000);

But looks 'incorrect/unsafe' eg. 0x1000 is an int and not even uintptr_t, I could fix this, but is there a better/safer method of casting ?

like image 257
darune Avatar asked Oct 23 '19 07:10

darune


People also ask

What is const void * in C?

const void is a type which you can form a pointer to. It's similar to a normal void pointer, but conversions work differently. For example, a const int* cannot be implicitly converted to a void* , but it can be implicitly converted to a const void* .

What can't you do on a void pointer?

Explanation: Because the void pointer is used to cast the variables only, So pointer arithmetic can't be done in a void pointer.

Can we free void pointer?

yes it is safe.


1 Answers

0x1000 is an int and not even uintptr_t, I could fix this, but is there a better/safer method of casting

0x1000 is int, and in reinterpret_cast<void*>(0x1000) the compiler emits a sign extension instruction (sign is 0 here) or a plain register load instruction with an immediate operand to make the value as wide as void*.

For many reasons the compiler cannot possibly know whether 0x1000 represents a valid address, so it has to comply and assume that it is a valid address.

Casting integers representing addresses to pointers with reinterpret_cast is currently the existing practice.

like image 169
Maxim Egorushkin Avatar answered Sep 24 '22 19:09

Maxim Egorushkin