cainsr2
cainsr2

Reputation: 55

Is it safe to use a reinterpret_cast if I can guarantee the correct type was used to allocate the memory?

I am trying to make my C++ code cross platform. On Windows I am using the Windows.h header file and on macOS and Linux I use the unistd.h header file.

I am calling a function if the OS is windows which takes a char* type. The equivalent call for mac and linux takes char**. I currently have a function that takes a void* type so that I can have 1 function for both cases. I then check the operating system and reinterpret_cast to the correct type.

void DoSomething(void* thing) {

  #if defined(__APPLE__) || defined(__linux__)

  // Init thing as char**
  thing = new char*[...];
    thing[0] = new char[...];
    .
    .
    .

  UnixFunction(reinterpret_cast<char**>(thing));

  #elif defined(_WIN32)

  // Init thing as char*
  thing = new char[...];
  WindowsFunction(reinterpret_cast<char*>(thing));
  #endif
}

int main() {

  void* thing;
  DoSomething(thing);

  return 0;

}

Regardless if I should do this, is this safe or is this undefined behavior?

Upvotes: 1

Views: 76

Answers (1)

John Zwinck
John Zwinck

Reputation: 249223

It sounds like what you're asking about would be safe. However, your code looks a bit off:

void DoSomething(void* thing) {
    thing = new char*[...];

That will leave the caller with no access to the allocated memory, because thing is an addressed the caller passed in but then you immediately overwrote the address, so you have no way to write into the memory the caller gave you, and/or the caller has no way to know what memory you allocated.

You could take (void*& thing) so that your changes to the pointer are visible to the caller, for example. Or just return the pointer from the function instead.

If you fix that design error, reinterpret_cast won't itself be a problem. You can even cast pointers to uintptr_t or intptr_t and back again using reinterpret_cast if you want a way to just pass addresses around without needing to know the type until you use them again.

Upvotes: 1

Related Questions