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.

8
  • 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. Commented Apr 5, 2023 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. Commented Apr 5, 2023 at 16:19
  • 1
    fyi C++ named requirements: ImplicitLifetimeType Commented Apr 5, 2023 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. Commented Apr 5, 2023 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. Commented Apr 5, 2023 at 19:17

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.