[英]valgrind Invalid write of size 8 in a allocated memory
我正在嘗試將新節點添加到我的鏈表中,但它給出了 memory 錯誤
我的結構和全局變量:
typedef struct word word;
struct word
{
char str[256];
word *next;
};
word *head = NULL;
word *cur = NULL;
function:
int addWord(char * str)
{
word *w = calloc(1, sizeof(w));
if(w == NULL)
{
return 0;
}
strcpy(w->str, str);
if(cur == NULL)
{
cur = w;
head = w;
}
else
{
puts("4");
cur->next = w;
puts("5");
cur = w;
puts("6");
}
return 1;
}
結果是:
...
4
5
6
4
==73913== Invalid write of size 8
==73913== at 0x109425: addWord (in /home/mz37/programming/godaphy/bin/godaphy.out)
==73913== by 0x109696: parseLine (in /home/mz37/programming/godaphy/bin/godaphy.out)
==73913== by 0x109351: main (in /home/mz37/programming/godaphy/bin/godaphy.out)
==73913== Address 0x4a6a880 is 96 bytes inside an unallocated block of size 4,188,096 in arena "client"
==73913==
5
6
我仍在尋找錯誤,我還沒有找到它
word *w = calloc(1, sizeof(w));
w
變量是word
指針類型,因此最多可能是四個或八個字節。 如果我們最終使用 128 位機器,它可能會更大,但要達到 2000+ 位還需要相當長的時間:-)
你可能想做:
word *w = calloc(1, sizeof(*w));
// note this ___^
*w
的類型是實際的類型word
,這將是您嘗試執行的正確大小。
而且,順便說一句,您可能想考慮盲目地將給定的任何字符串復制到只能容納 256 個字符的 memory 塊中的智慧。 更安全的選擇是:
strncpy(w->str, str, sizeof(w->str) - 1);
// Would normally also do something like:
// w->str[sizeof(w->str) - 1] = '\0';
// but calloc() makes that superfluous.
生成的 function(包括壓縮)將遵循以下幾行:
int addWord(char *str) {
word *w;
// Option to fail if string too big, rather than truncate.
//if (strlen(str) >= sizeof(w->str)
// return 0;
// Allocate and check.
if ((w = calloc(1, sizeof(*w))) == NULL)
return 0;
// Copy in string, truncate if too big.
strncpy(w->str, str, sizeof(w->str) - 1);
// Make new list if currently empty, otherwise add it, then flag success.
if(cur == NULL) {
cur = head = w;
} else {
cur->next = w;
cur = w;
}
return 1;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.