faboussard / 42-irc

3 stars 1 forks source link

When already launched, the new server launch leaks #33

Closed melobern closed 2 weeks ago

melobern commented 2 weeks ago

➜ GIT_IRC git:(part) ✗ valgrind ./ircserv 6667 pass

==551206== Memcheck, a memory error detector
==551206== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==551206== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==551206== Command: ./ircserv 6667 pass
==551206== 
Failed to bind socket. Port might be used elsewhere
Server <3> Disconnected
==551206== 
==551206== HEAP SUMMARY:
==551206==     in use at exit: 2,709 bytes in 28 blocks
==551206==   total heap usage: 50 allocs, 22 frees, 87,951 bytes allocated
==551206== 
==551206== LEAK SUMMARY:
==551206==    definitely lost: 0 bytes in 0 blocks
==551206==    indirectly lost: 0 bytes in 0 blocks
==551206==      possibly lost: 220 bytes in 2 blocks
==551206==    still reachable: 2,489 bytes in 26 blocks
==551206==                       of which reachable via heuristic:
==551206==                         stdstring          : 76 bytes in 1 blocks
==551206==         suppressed: 0 bytes in 0 blocks
==551206== Rerun with --leak-check=full to see details of leaked memory
==551206== 
==551206== For lists of detected and suppressed errors, rerun with: -s
==551206== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

This happens if any error is thrown in Server::createSocket :

  if (_socketFd == -1) {
    throw std::runtime_error("Failed to create socket");
  }

  int en = 1;
  if (setsockopt(_socketFd, SOL_SOCKET, SO_REUSEADDR, &en, sizeof(en)) == -1) {
    throw std::runtime_error("Failed to set option SO_REUSEADDR on socket");
  }

  if (fcntl(_socketFd, F_SETFL, O_NONBLOCK) == -1) {
    throw std::runtime_error("Failed to set option O_NONBLOCK on socket");
  }

  if (bind(_socketFd, (struct sockaddr *)&_address, sizeof(_address)) == -1) {
    throw std::runtime_error(
        "Failed to bind socket. Port might be used elsewhere");
  }

  if (listen(_socketFd, SOMAXCONN) == -1) {
    throw std::runtime_error("Failed to listen on socket");
  }