If I use malloc in C++, what should I use for casting?

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <cstdio>
#include <cstdlib>
 
void main()
{ 
    // 1
    int* p1 = static_cast<int*>(std::malloc(sizeof(int)*10));
    std::free(p1);
 
    // 2
    int* p2 = (int*)(std::malloc(sizeof(int)*10));
    std::free(p2);
}


Which is more safety and preferred?
and if possible I wanna know the simple reason, please.
Last edited on
In general, favour using a named cast (here, static_cast) over C-style and function-style casts.

If you must use a cast, use a named cast

Reason: Readability. Error avoidance. Named casts are more specific than a C-style or functional cast, allowing the compiler to catch some errors.

https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-casts-named



// JLBorges
Thanks! it helped for me.
Your question having been answered, I would nonetheless be remiss, give that your interest is:

more safety

if I did not mention that using malloc at all is definitely on the less safe side of things. This being C++, there are much safer options and the only reason I can think of to use malloc is if you have to use some existing library that forces you to provide it with just a big lump of raw space on the heap.
Topic archived. No new replies allowed.