Talk:cpp/memory/c/malloc

The example code is UB because it accesses int objects that were never created. See for a discussion of the current state of object creation with references to the standard. To fix the issue one would need to use placement new to create objects:

— Preceding unsigned comment added by 93.220.18.148 (talk • contribs)
 * p0593r2 does not just point out that virtually all code that uses malloc is undefined in C++17, it's also a proposed fix. I'd say it's unclear if changing the malloc examples would be helpful given that the fix is inevitable one way or another. Maybe a note for passing language-lawyers would help? --Cubbi (talk) 14:16, 23 May 2018 (PDT)
 * Or maybe we can sidestep the issue and show a case where you absolutely need to use placement new and explicit destructor call instead. Demonstrating how hard it is outside of toy examples with trivial types may help dissuading people from using it. T. Canens (talk) 14:32, 23 May 2018 (PDT)
 * gave that a try --Cubbi (talk) 11:33, 24 May 2018 (PDT)

calling the destructor of std::string
Wouldn't it be better to call the destructor of std::string as:

p[i - 1].std::string::~string;

instead of:

p[i - 1].~basic_string;

The former is keeping the use of std::string typedef as is without the need to introduce basic_string into this example.

Amirk (talk) 15:07, 12 January 2020 (PST)
 * (without using-declaration) fails to compile in all versions of clang. I have added a using-declaration and used . --Fruderica (talk) 20:36, 12 January 2020 (PST)

Better yet use std::destroy_at to call the destructor on the static type of p[i-1]. IMHO explicit calls to destructor should be discouraged even more than explicit calls to new. NickH (talk) 23:25, 12 January 2020 (PST)