From 6dd7c51aedcf48c5347bc430d910a9743ec5af29 Mon Sep 17 00:00:00 2001 From: Dimitar Krastev Date: Thu, 9 Jan 2025 03:00:56 +0200 Subject: [PATCH] Changed `IPNetwork` copy assignment implementation to copy-and-swap. (#1681) * Changed `IPNetwork` copy assignment implementation to copy-and-swap the internal network. This change fixes use of memory after being freed in case of self-assignment and provides a strong exception guarantee. * Removed the temporary variable. --- Common++/header/IpAddress.h | 26 ++++---------------------- 1 file changed, 4 insertions(+), 22 deletions(-) diff --git a/Common++/header/IpAddress.h b/Common++/header/IpAddress.h index 6cafb2ed7d..29096b524a 100644 --- a/Common++/header/IpAddress.h +++ b/Common++/header/IpAddress.h @@ -707,18 +707,9 @@ namespace pcpp /// @return A reference to the assignee IPNetwork& operator=(const IPv4Network& other) { - if (m_IPv4Network) - { - m_IPv4Network = nullptr; - } - - if (m_IPv6Network) - { - m_IPv6Network = nullptr; - } - + // Create the new instance first to maintain strong exception guarantee. m_IPv4Network = std::unique_ptr(new IPv4Network(other)); - + m_IPv6Network = nullptr; return *this; } @@ -727,18 +718,9 @@ namespace pcpp /// @return A reference to the assignee IPNetwork& operator=(const IPv6Network& other) { - if (m_IPv4Network) - { - m_IPv4Network = nullptr; - } - - if (m_IPv6Network) - { - m_IPv6Network = nullptr; - } - + // Create the new instance first to maintain strong exception guarantee. m_IPv6Network = std::unique_ptr(new IPv6Network(other)); - + m_IPv4Network = nullptr; return *this; }