Markus Fischer
Markus Fischer

Reputation: 29

Delete and cast. Will delete free the right amount of bytes?

Will delete free the right amount of bytes ?

unique_ptr<sockaddr_in> up = make_unique<sockaddr_in>();        
// or unique_ptr<sockaddr_in> up( new sockaddr_in ); ???

/* 
    Some stuff 
    sockaddr and sockaddr_in are two different types of struct and are not relateted 
*/

sockaddr *p = reinterpret_cast<sockaddr *>( up.release() );

delete p; 

Upvotes: 1

Views: 162

Answers (2)

rustyx
rustyx

Reputation: 85521

In most cases, sockaddr is not a base class of sockaddr_in (source 1, 2, 3):

struct sockaddr {
        ushort  sa_family;
        char    sa_data[14];
};

struct sockaddr_in {
        short   sin_family;
        u_short sin_port;
        struct  in_addr sin_addr;
        char    sin_zero[8];
};

Therefore according to [expr.delete]/p3 the behavior of the program is undefined:

... if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.


With that said, in many cases the built-in operator delete simply delegates to free, which does not need the size, and the program will appear to work as intended (though when coding in C++ we really prefer to stay in the realm of defined behavior).

Why not simply let the unique_ptr do its job and delete the sockaddr_in upon destruction?

Upvotes: 4

Swift - Friday Pie
Swift - Friday Pie

Reputation: 14688

It would delete sizeof(sockaddr) bytes , unless sockaddr is base type of sockaddr_in and got a virtual destructor. Wherever that would succeed otherwise or not is undefined. After you did reinterpret_cast, sockaddr* is the static type of pointer. question is , does it have different dynamic type or not.

Upvotes: 1

Related Questions