I was told that the following code has undefined behavior until C++20:
int *p = (int*)malloc(sizeof(int));
*p = 10;
Is that true?
The argument was that the lifetime of the int object is not started before assigning the value to it (P0593R6). To fix the problem, placement new should be used:
int *p = (int*)malloc(sizeof(int));
new (p) int;
*p = 10;
Do we really have to call a default constructor that is trivial to start the lifetime of the object?
At the same time, the code does not have undefined behavior in pure C. But, what if I allocate an int in C code and use it in C++ code?
// C source code:
int *alloc_int(void)
{
int *p = (int*)malloc(sizeof(int));
*p = 10;
return p;
}
// C++ source code:
extern "C" int *alloc_int(void);
auto p = alloc_int();
*p = 20;
Is it still undefined behavior?
int? No. Forstd::string? Yes.int, also yes. It's just that it won't cause problems in practice if you don't do it. Forstd::string, it just will obviously cause problems.int *p = (int*)malloc(sizeof(int)); p = new(p) int;? I once realized that not assigning the result of placement new may cause fatal effects as well (although it might look a bit silly).