C (Linux) - valgrind:条件跳转或移动取决于重新分配后的未初始化值

C (Linux) - valgrind: Conditional jump or move depends on uninitialised value(s) after realloc

在我的程序上 运行 valgrind 之后,我得到以下输出:

==17731== Thread 2:
==17731== Conditional jump or move depends on uninitialised value(s)
==17731==    at 0x401CD8: poll_existing_connections (connmgr.c:112)
==17731==    by 0x401ACD: connmgr_listen (connmgr.c:69)
==17731==    by 0x40161A: connmgr (main.c:148)
==17731==    by 0x5545609: start_thread (in /usr/lib64/libpthread-2.22.so)
==17731==  Uninitialised value was created by a heap allocation
==17731==    at 0x4C2AB8B: realloc (vg_replace_malloc.c:785)
==17731==    by 0x401B64: poll_new_connection (connmgr.c:85)
==17731==    by 0x401AB9: connmgr_listen (connmgr.c:68)
==17731==    by 0x40161A: connmgr (main.c:148)
==17731==    by 0x5545609: start_thread (in /usr/lib64/libpthread-2.22.so)
==17731== 

我怀疑我使用 realloc 的方式有问题。我开始谷歌搜索并尝试了一些我发现对其他用户有用的解决方案,但这些解决方案都不适合我。 我也尝试过使用不同的方式(malloc 新内存并将数组的旧值复制到新内存中)但是这导致了 valgrind 的相同类型的错误。

对可能出现的问题有什么建议吗?

我的代码 (connmgr.c:112):

sensor_conn_t * sensor_conn = dpl_get_element_at_index(sensor_sockets, i);
poll_action = poll_list[i].revents == POLLIN;
if(poll_action == POLLIN) { 
    //The sensor sent some data
    read_data(sensor_conn, i, buffer);
} else { 
    //No data received from the sensor
    check_timeout();
}

我的代码(connmgr.c:85):

//Add the new connection to an array so that it is pollable
struct pollfd * new_poll_list = realloc(poll_list, (nb_connections + 1) * sizeof(struct pollfd));
assert(new_poll_list != NULL);
poll_list = new_poll_list;

tcp_get_sd(client, &poll_list[nb_connections].fd);
poll_list[nb_connections].events = POLLIN;

您正在调用realloc,但您没有初始化比原始缓冲区大的缓冲区内容。基本上,您 new_poll_list 进入的所有内存都未初始化。

调用 realloc 后,确保初始化原始缓冲区大小之后的区域。

这里你正在初始化一个字段:

poll_list[nb_connections].events = POLLIN;

这里您正在测试一个字段的内容:

poll_action = poll_list[i].revents == POLLIN;
  if(poll_action == POLLIN)

都很好,但是不是同一个领域