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

标签 c linux valgrind

在我的程序上运行 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/

相关文章:

linux - 如何将文件从给定目录复制到目标目录的随机目录

android - 为 android 构建 valgrind 时未定义 __ANDROID__

c - 是否有任何 C API 来检查源 IP 地址是否来自同一网络?

c - 如何等待帧和报警信号

c 文件中内联汇编代码的编译错误,可能与分支有关

c++ - 如何让 Valgrind 调试器逐步执行程序

python - 如何在 python 中使用 valgrind?

c - Uart 与 C 语言中的十六进制代码通信

linux - 在 bash 脚本中重用虚拟文件

linux - Centos 6.5如何自动启动elasticsearch?