2016-05-30 32 views
1

之後依賴於未初始化值(S)在我的程序運行的valgrind後,我得到了以下的輸出:C(Linux)的 - 的valgrind:條件跳轉或移動realloc的

==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== 

我supsected出事了與我的方式使用realloc。我開始使用Google,並嘗試了一些我發現可以爲其他用戶工作的解決方案,但這些解決方案都不適合我。 我也嘗試過使用不同的方法(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; 
+0

您將'poll_list'放大了,但是,您在哪裏初始化新元素? 'poll_list [i] .revents'在哪裏初始化? – Schwern

+1

@Schwern我教過,我用這些行初始化了一切:tcp_get_sd(client,&poll_list [nb_connections] .fd); poll_list [nb_connections] .events = POLLIN; 原來我忘了初始化poll_list [i] .revents 非常感謝,這解決了我的問題。 – TrueStory

回答

0

要調用realloc的,但你沒有初始化內容大於原始緩衝區的緩衝區。基本上,你已經增長了new_poll_list的所有內存都是未初始化的。

調用realloc之後,請確保初始化原始緩衝區大小之後的區域。

+0

感謝您的快速響應,我教導我使用這些tzo行初始化它: tcp_get_sd(client,&poll_list [nb_connections] .fd); poll_list [nb_connections] .events = POLLIN; 顯然我做錯了什麼。你如何建議我初始化它們? (我對C來說是一個新手) – TrueStory

+0

@Jonas在斷言之後,明確地將poll_list [nb_connections]結構體的每個元素設置爲一個值。 – bodangly

+0

正如你和@Schwern所建議的,我沒有初始化所有東西(忘記了poll_list [i] .revent)。 – TrueStory

0

這裏要初始化場:

poll_list[nb_connections].events = POLLIN; 

這裏你測試字段的內容:

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

都很好,但他們不一樣的領域

+0

謝謝,那的確是問題所在 – TrueStory

相關問題