• Guilherme Maciel Ferreira's avatar
    Fix memory leak on Socket_new() · af53c72a
    Guilherme Maciel Ferreira authored
    There is a memory leak on Socket_new(). The leak is caused by the lost of a
    reference to result pointer, returned from getaddrinfo(3). The freeaddrinfo(3)
    requires a pointer to the first result's element. However, this reference is
    lost when replaced by res.
    
    The Valgrind's memory leak report:
    
      ==15305== HEAP SUMMARY:
      ==15305==     in use at exit: 60 bytes in 1 blocks
      ==15305==   total heap usage: 205 allocs, 204 frees, 128,834 bytes allocated
      ==15305==
      ==15305== 60 bytes in 1 blocks are definitely lost in loss record 1 of 1
      ==15305==    at 0x4024F20: malloc (vg_replace_malloc.c:236)
      ==15305==    by 0x419650F: gaih_inet (getaddrinfo.c:1253)
      ==15305==    by 0x41994F4: getaddrinfo (getaddrinfo.c:2425)
      ==15305==    by 0x4036D3A: Socket_new (Socket.c:607)
      ==15305==    by 0x40352A4: MQTTProtocol_connect (MQTTProtocolOut.c:97)
      ==15305==    by 0x402FF71: MQTTClient_connectURIVersion (MQTTClient.c:792)
      ==15305==    by 0x403033F: MQTTClient_connectURI (MQTTClient.c:1025)
      ==15305==    by 0x4030496: MQTTClient_connect (MQTTClient.c:1086)
      ==15305==    by 0x8048A31: myconnect (stdoutsub.c:98)
      ==15305==    by 0x8048C73: main (stdoutsub.c:146)
      ==15305==
      ==15305== LEAK SUMMARY:
      ==15305==    definitely lost: 60 bytes in 1 blocks
      ==15305==    indirectly lost: 0 bytes in 0 blocks
      ==15305==      possibly lost: 0 bytes in 0 blocks
      ==15305==    still reachable: 0 bytes in 0 blocks
      ==15305==         suppressed: 0 bytes in 0 blocks
      ==15305==
      ==15305== For counts of detected and suppressed errors, rerun with: -v
      ==15305== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 19 from 10)
    
    Keeping the result pointer unchanged, pointing to the first element. And
    updating the res pointer only, we get a clean report from Valgrind:
    
      ==15924== HEAP SUMMARY:
      ==15924==     in use at exit: 0 bytes in 0 blocks
      ==15924==   total heap usage: 334 allocs, 334 frees, 131,753 bytes allocated
      ==15924==
      ==15924== All heap blocks were freed -- no leaks are possible
      ==15924==
      ==15924== For counts of detected and suppressed errors, rerun with: -v
      ==15924== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 19 from 10)
    Signed-off-by: 's avatarGuilherme Maciel Ferreira <guilherme.maciel.ferreira@gmail.com>
    af53c72a
Socket.c 21.3 KB