0

Is this code undefined behaviour in C++?

...
float *f = (float*)malloc(sizeof(float) * 3);
if (f == NULL)
{
  // handle error
}

f[0] = 1.0;
f[1] = 2.0;
f[2] = 3.0;
...
// code using f[0] to f[2] ...
...

IMO this is legal for POD types (like float, double, int etc.).

I know it's ugly and that it shouldn't be used.

genpfault
  • 51,148
  • 11
  • 85
  • 139
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • Yeah, it's the constant NULL check that turned me off from using `malloc` (and any similar functions) forever, unless it is required for placement-new. – PaulMcKenzie Apr 05 '23 at 16:17
  • 3
    C++20 started fixing some object lifetime issues via the concept of implicit object creation. That'd be the relevant search term. – chris Apr 05 '23 at 16:19
  • The relevant sections in the standard are [`c.malloc`](https://eel.is/c++draft/c.malloc) (quote: _"These functions implicitly create objects…"_) and [`intro.object`](https://eel.is/c++draft/intro.object) (quote: _"For each operation that is specified as implicitly creating objects, that operation implicitly creates and starts the lifetime of zero or more objects of implicit-lifetime types…"_), I think. – heap underrun Apr 05 '23 at 16:26
  • @heapunderrun yes, https://stackoverflow.com/questions/60626834/unspecified-implicit-object-creation looks interesting – Jabberwocky Apr 05 '23 at 16:29
  • your question asks "is this ...some code using `float`... legal? I know it is legal eg for `float`". Do you mean you know its ok for a single `float` and now ask about the array ? – 463035818_is_not_an_ai Apr 05 '23 at 17:08
  • 1
    fyi [C++ named requirements: ImplicitLifetimeType](https://en.cppreference.com/w/cpp/named_req/ImplicitLifetimeType) – Richard Critten Apr 05 '23 at 18:00
  • 1
    It's worth noting that you can call new without a type, `void* buffer = operator new(64)`. Very useful if you want to use C++ idioms with raw buffers or placement new. It also supports `std::nothrow` if you prefer to check for nulls instead of exception handling. – vandench Apr 05 '23 at 18:30
  • 1
    @463035818_is_not_a_number _I know it is legal eg for float_ : no I didn't write this, I wrote _In My Opioion it's legal_, so I wasn't sure. – Jabberwocky Apr 05 '23 at 19:17

0 Answers0