Commit 2be5c97d authored by Dennis Jenkins's avatar Dennis Jenkins

Fixed memory leak of 'struct addrinfo' from ::getaddrinfo() in Listener::bind().

parent c390b975
...@@ -26,6 +26,42 @@ ...@@ -26,6 +26,42 @@
namespace Pistache { namespace Pistache {
// Wrapper around 'getaddrinfo()' that handles cleanup on destruction.
class AddrInfo {
public:
// Disable copy and assign.
AddrInfo(const AddrInfo &) = delete;
AddrInfo& operator=(const AddrInfo &) = delete;
// Default construction: do nothing.
AddrInfo() : addrs(nullptr) {}
~AddrInfo() {
if (addrs) {
::freeaddrinfo(addrs);
}
}
// Call "::getaddrinfo()", but stash result locally. Takes the same args
// as the first 3 args to "::getaddrinfo()" and returns the same result.
int invoke(const char *node, const char *service,
const struct addrinfo *hints) {
if (addrs) {
::freeaddrinfo(addrs);
addrs = nullptr;
}
return ::getaddrinfo(node, service, hints, &addrs);
}
const struct addrinfo *get_info_ptr() const {
return addrs;
}
private:
struct addrinfo *addrs;
};
class Port { class Port {
public: public:
Port(uint16_t port = 0); Port(uint16_t port = 0);
......
...@@ -189,13 +189,14 @@ Listener::bind(const Address& address) { ...@@ -189,13 +189,14 @@ Listener::bind(const Address& address) {
const auto& host = addr_.host(); const auto& host = addr_.host();
const auto& port = addr_.port().toString(); const auto& port = addr_.port().toString();
struct addrinfo *addrs; AddrInfo addr_info;
TRY(::getaddrinfo(host.c_str(), port.c_str(), &hints, &addrs));
TRY(addr_info.invoke(host.c_str(), port.c_str(), &hints));
int fd = -1; int fd = -1;
addrinfo *addr; const addrinfo * addr = nullptr;
for (addr = addrs; addr; addr = addr->ai_next) { for (addr = addr_info.get_info_ptr(); addr; addr = addr->ai_next) {
fd = ::socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); fd = ::socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
if (fd < 0) continue; if (fd < 0) continue;
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment