[PATCH] libga68: Fix fd leak in posix fconnect

Jose E. Marchesi jemarch@gnu.org
Sat Apr 12 06:53:41 GMT 2025


Hi Pietro.

> The function would leak the socket fd if any error happened after its creation.
> Discovered by adding `-fanalyzer' to the library CFLAGS.
>
> ChangeLog:
>
> 	* libga68/ga68-posix.c (_libga68_posixfconnect): Fix fd leak on error.
>
> Signed-off-by: Pietro Monteiro <pietro@sociotechnical.xyz>

Applied on your behalf.
Thanks for the patch!


> ---
>  libga68/ga68-posix.c | 15 ++++++++++-----
>  1 file changed, 10 insertions(+), 5 deletions(-)
>
> diff --git a/libga68/ga68-posix.c b/libga68/ga68-posix.c
> index 78f0ac2b178..166f72787e8 100644
> --- a/libga68/ga68-posix.c
> +++ b/libga68/ga68-posix.c
> @@ -340,7 +340,7 @@ _libga68_posixfconnect (uint32_t *str, size_t len, size_t stride,
>    int fd = socket (AF_INET, SOCK_STREAM, 0);
>    _libga68_errno = errno;
>    if (fd < 0)
> -    return -1;
> +    goto end;
>  
>    /* Lookup the specified host.  */
>    char *host = _libga68_malloc (u8len + 1);
> @@ -350,10 +350,8 @@ _libga68_posixfconnect (uint32_t *str, size_t len, size_t stride,
>    if (server == NULL)
>      {
>        _libga68_errno = h_errno;
> -      _libga68_free (host);
> -      return -1;
> +      goto close_fd;
>      }
> -  _libga68_free (host);
>  
>    /* Connect the socket to the server.  */
>    struct sockaddr_in serv_addr;
> @@ -367,8 +365,15 @@ _libga68_posixfconnect (uint32_t *str, size_t len, size_t stride,
>  		     sizeof (serv_addr));
>    _libga68_errno = errno;
>    if (res == -1)
> -    return -1;
> +    goto close_fd;
> +
> + close_fd:
> +  close (fd);
> +  fd = -1;
> +
> +  _libga68_free (host);
>  
>    /* Return the file descriptor for the socket.  */
> + end:
>    return fd;
>  }


More information about the Algol68 mailing list