ibacm: Fix realloc() return value without detecting null pointer In expand() function of ibacm/src/parse.c, the return value of realloc() is directly assigned back to the original pointer without null check. If realloc() fails and returns NULL, the original memory pointer is lost, causing memory leak. Additionally, the subsequent strcpy() will dereference a NULL pointer, leading to segmentation fault. Use a temporary variable new_buf to receive realloc() return value and check for NULL before assignment. On failure, free the original buffer, reset output parameters, and return NULL. Also add NULL check for expand() return value in parse() to prevent dereferencing NULL pointer in subsequent memcpy(). Signed-off-by: Dai Yanlong <daiyanlong@kylinos.cn>
diff --git a/ibacm/src/parse.c b/ibacm/src/parse.c index 15aab17..1c00807 100644 --- a/ibacm/src/parse.c +++ b/ibacm/src/parse.c
@@ -36,7 +36,7 @@ { char buf[256]; char *str_buf = NULL; - char *token, *tmp; + char *token, *tmp, *new_buf; int from, to, width; int size = 0, cnt = 0; @@ -54,7 +54,14 @@ while (from <= to) { snprintf(buf, sizeof buf, "%s%0*d", basename, width, from); - str_buf = realloc(str_buf, size + strlen(buf)+1); + new_buf = realloc(str_buf, size + strlen(buf)+1); + if (!new_buf) { + free(str_buf); + *str_size = 0; + *str_cnt = 0; + return NULL; + } + str_buf = new_buf; strcpy(&str_buf[size], buf); from++; @@ -101,6 +108,8 @@ cnt = 1; } else { str_buf = expand(cpy, next, &cnt, &str_size); + if (!str_buf) + goto out_cpy; } ptrs = malloc((sizeof str_buf * (cnt + 1)) + str_size);