在我的程序上运行 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 后,确保初始化原始缓冲区大小之后的区域。
关于C(Linux)-valgrind : Conditional jump or move depends on uninitialised value(s) after realloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37534568/