2013-05-15 52 views
4

我的程序在人們從文件中讀取並保存自己的信息到人的結構,看起來像這樣:Valgrind的多個「無效的寫入/讀取尺寸爲1」的錯誤

struct person 
{ 
    char *fname; 
    char *lname; 
    int id; 
}; 
typedef struct person Person; 

這些人在一個陣列舉行者和功能來填充該陣列看起來像這樣(總變量是的人的從文件計數的總數):

Person* fillArray(int total, FILE *fin) 
{ 
    rewind(fin); 
    int i; 
    char temp[50]; 
    char temp2[50]; 
    Person *p = (Person*) calloc(total, sizeof(Person)); 
    for(i = 0; i < total; i++) 
    { 
     fscanf(fin, "%s", temp); 
     p[i].fname = (char *) calloc(strlen(temp)+1, sizeof(char)); 
     strcpy(p[i].fname, temp); 
     fscanf(fin, "%s", temp2); 
     p[i].lname = (char *) calloc(strlen(temp)+1, sizeof(char)); 
     strcpy(p[i].lname, temp2); 
     fscanf(fin, "%d", &(p + i)->id); 
    } 
    return p; 
} 

我清理用於我的所有存儲器和I釋放calloc爲「\ 0」在臨時字符串的末尾。不知道爲什麼我得到這些錯誤:

HEAP SUMMARY: 
==4736==  in use at exit: 0 bytes in 0 blocks 
==4736== total heap usage: 8 allocs, 8 frees, 414 bytes allocated 
==4736== 
==4736== All heap blocks were freed -- no leaks are possible 
==4736== 
==4736== ERROR SUMMARY: 10 errors from 2 contexts (suppressed: 0 from 0) 
==4736== 
==4736== 3 errors in context 1 of 2: 
==4736== Invalid write of size 1 
==4736== at 0x402C6E8: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so) 
==4736== by 0x804898E: fillArray (cscd240_s13_lab11Functions.c:30) 
==4736== by 0x8048731: main (cscd240_s13_lab11Tester.c:13) 
==4736== Address 0x41ef24f is 3 bytes after a block of size 4 alloc'd 
==4736== at 0x402A5E6: calloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so) 
==4736== by 0x804896A: fillArray (cscd240_s13_lab11Functions.c:29) 
==4736== by 0x8048731: main (cscd240_s13_lab11Tester.c:13) 
==4736== 
==4736== 
==4736== 7 errors in context 2 of 2: 
==4736== Invalid write of size 1 
==4736== at 0x402C6C3: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so) 
==4736== by 0x804898E: fillArray (cscd240_s13_lab11Functions.c:30) 
==4736== by 0x8048731: main (cscd240_s13_lab11Tester.c:13) 
==4736== Address 0x41ef24c is 0 bytes after a block of size 4 alloc'd 
==4736== at 0x402A5E6: calloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so) 
==4736== by 0x804896A: fillArray (cscd240_s13_lab11Functions.c:29) 
==4736== by 0x8048731: main (cscd240_s13_lab11Tester.c:13) 
==4736== 
==4736== ERROR SUMMARY: 10 errors from 2 contexts (suppressed: 0 from 0) 

謝謝你的幫助。我查看了幾個線程,其中大部分都是關於字符結尾的'\ 0'的calloc/mallocing。我這樣做,但是當我用qsort()排序Person數組時,我仍然得到這些錯誤和更多。我很抱歉,如果這是以前問過的同樣的問題,我找不到線程。

回答

8

您使用了錯誤的長度爲第二部分的分配,

fscanf(fin, "%s", temp2); 
p[i].lname = (char *) calloc(strlen(temp)+1, sizeof(char)); 
strcpy(p[i].lname, temp2); 

應使用strlen(temp2);那裏。

+0

用了一個半小時盯着那個,一定是誤刪了2個。把它放在我最後一個版本的程序上。謝謝!在7分鐘內檢查雅。 –