Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using malloc for int undefined behavior until C++20

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?

like image 398
anton_rh Avatar asked Aug 12 '20 14:08

anton_rh


People also ask

What is undefined behavior in c++?

So, in C/C++ programming, undefined behavior means when the program fails to compile, or it may execute incorrectly, either crashes or generates incorrect results, or when it may fortuitously do exactly what the programmer intended.

Does malloc invoke constructor?

Calling Constructors: new calls constructors, while malloc() does not. In fact primitive data types (char, int, float.. etc) can also be initialized with new.

What is ill formed c++?

An ill-formed program is a C++ program that is not well-formed; that is, a program not constructed according to the syntax rules, diagnosable semantic rules, and the one-definition rule.


1 Answers

Is it true?

Yes. Technically speaking, no part of:

int *p = (int*)malloc(sizeof(int)); 

actually creates an object of type int, so dereferencing p is UB since there is no actual int there.

Do we really have to call default constructor that is trivial to start the life time of the object?

Do you have to per the C++ object model to avoid undefined behavior pre-C++20? Yes. Will any compiler actually cause harm by you not doing this? Not that I'm aware of.

[...] Is it still undefined behavior?

Yes. Pre-C++20, you still didn't actually create an int object anywhere so this is UB.

like image 176
Barry Avatar answered Sep 20 '22 17:09

Barry