From 4141787fb1b4fc7d15322a69e68897ecd61ec2e4 Mon Sep 17 00:00:00 2001 From: Neria Ifrah Date: Mon, 18 May 2026 11:06:38 +0300 Subject: [PATCH] Fix freeaddrinfo(NULL) in _modbus_tcp_pi_connect When getaddrinfo() fails in _modbus_tcp_pi_connect, the error path calls freeaddrinfo(ai_list) unconditionally. POSIX leaves the contents of *res unspecified on getaddrinfo() failure, and freeaddrinfo(NULL) is undefined behaviour. On musl libc this causes a segfault, so a hostname that fails to resolve crashes the host application instead of returning -1 with errno=ECONNREFUSED as documented. This is the same defect that was fixed for the server-side mirror function modbus_tcp_pi_listen in commit 26dc8a5 ("Check if ai_list is null before freeing it (#831)"). The client-side mirror has the byte-for-byte identical error-handling code and was overlooked. Apply the same guard pattern to _modbus_tcp_pi_connect to complete the fix on the client path. Affects Alpine, OpenWrt, and other musl-based deployments, which are core libmodbus targets. Closes # --- src/modbus-tcp.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/modbus-tcp.c b/src/modbus-tcp.c index f1ec959b..a43faaf1 100644 --- a/src/modbus-tcp.c +++ b/src/modbus-tcp.c @@ -445,7 +445,9 @@ static int _modbus_tcp_pi_connect(modbus_t *ctx) fprintf(stderr, "Error returned by getaddrinfo: %d\n", rc); #endif } - freeaddrinfo(ai_list); + if (ai_list != NULL) { + freeaddrinfo(ai_list); + } errno = ECONNREFUSED; return -1; }