Fix memory leak when creating a socket fails.

Previously, AddressSanitizer flagged leaks when running
tests/test_many_sockets.cpp.
This commit is contained in:
Brian Silverman 2015-07-22 11:18:48 -07:00
parent c05a475bf7
commit 773a06fc23
2 changed files with 28 additions and 16 deletions

View File

@ -133,28 +133,37 @@ zmq::signaler_t::signaler_t ()
#endif #endif
} }
// This might get run after some part of construction failed, leaving one or
// both of r and w retired_fd.
zmq::signaler_t::~signaler_t () zmq::signaler_t::~signaler_t ()
{ {
#if defined ZMQ_HAVE_EVENTFD #if defined ZMQ_HAVE_EVENTFD
if (r == retired_fd) return;
int rc = close_wait_ms (r); int rc = close_wait_ms (r);
errno_assert (rc == 0); errno_assert (rc == 0);
#elif defined ZMQ_HAVE_WINDOWS #elif defined ZMQ_HAVE_WINDOWS
const struct linger so_linger = { 1, 0 }; if (w != retired_fd) {
int rc = setsockopt (w, SOL_SOCKET, SO_LINGER, const struct linger so_linger = { 1, 0 };
(const char *) &so_linger, sizeof so_linger); int rc = setsockopt (w, SOL_SOCKET, SO_LINGER,
// Only check shutdown if WSASTARTUP was previously done (const char *) &so_linger, sizeof so_linger);
if (rc == 0 || WSAGetLastError () != WSANOTINITIALISED) { // Only check shutdown if WSASTARTUP was previously done
wsa_assert (rc != SOCKET_ERROR); if (rc == 0 || WSAGetLastError () != WSANOTINITIALISED) {
rc = closesocket (w); wsa_assert (rc != SOCKET_ERROR);
wsa_assert (rc != SOCKET_ERROR); rc = closesocket (w);
rc = closesocket (r); wsa_assert (rc != SOCKET_ERROR);
wsa_assert (rc != SOCKET_ERROR); if (r == retired_fd) return;
} rc = closesocket (r);
wsa_assert (rc != SOCKET_ERROR);
}
#else #else
int rc = close_wait_ms (w); if (w != retired_fd) {
errno_assert (rc == 0); int rc = close_wait_ms (w);
rc = close_wait_ms (r); errno_assert (rc == 0);
errno_assert (rc == 0); }
if (r != retired_fd) {
rc = close_wait_ms (r);
errno_assert (rc == 0);
}
#endif #endif
} }

View File

@ -154,8 +154,11 @@ zmq::socket_base_t *zmq::socket_base_t::create (int type_, class ctx_t *parent_,
mailbox_t *mailbox = dynamic_cast<mailbox_t*> (s->mailbox); mailbox_t *mailbox = dynamic_cast<mailbox_t*> (s->mailbox);
if (mailbox != NULL && mailbox->get_fd () == retired_fd) if (mailbox != NULL && mailbox->get_fd () == retired_fd) {
s->destroyed = true;
delete s;
return NULL; return NULL;
}
return s; return s;
} }