Is the following well defined behavior?
#include <cstdlib>
#include <iostream>
void reallocate_something(void *&source_and_result, size_t size) {
void *dest = malloc(size);
memcpy(dest, source_and_result, size);
free(source_and_result);
source_and_result = dest;
}
void reallocate_something(int *&source_and_result, size_t size) {
// I the cast safe in this use case?
reallocate_something(reinterpret_cast<void*&>(source_and_result), size);
}
int main() {
const size_t size = 4 * sizeof(int);
int *start = static_cast<int*>(malloc(size));
*start = 0;
std::cout << start << ' ' << *start << '\n';
reallocate_something(start, size);
std::cout << start << ' ' << *start << '\n';
return 0;
}
The code uses a reinterpret_cast
to pass a reference to a pointer and re-allocate it, free it, and set it to the new area allocated. Is this well defined?
In particular A static_cast
would work if I did not want to pass a reference, and that would be well defined.
The tag is C++, and I'm asking about this code as-is within the C++ standard.