2011-04-25 69 views
0

Valgrind在這段代碼中檢測到大小爲1的無效寫入。 在此,我讀了文件,其中第一行是我不需要,和下面的行定義3串1個INT(TOTAL_SPACE),我需要把這個結構:valgrind在這段代碼中寫入錯誤無效

typedef struct 
{ 
    char username[40]; 
    char password[40]; 
    char token[40];  
    pid_t logged_pid;  
    int total_space;  
    int used_space;  
} User; 

的文件是這樣的(每個字上新的生產線,抱歉,但我還是不明白如何格式化文本和代碼):

pass 
username1 
password1 
token1delczzzzozoc 
4500000 
username2 
pasword2222 
token2efwerfg 
trg 
1000000 

下面是代碼:Valgrind的破口大罵只在第一個4行!在第一個字符「e」中:它有什麼問題?

User *user = NULL; 
int n = 0; 
int k = 0; 
char input; 
FILE *file;    

if(!(file = fopen(USERS, "r"))) logMmboxd("opening USERS failed\n", 1); 
else        logMmboxd("opened USERS\n", 0); 

/* file pointer at the second line, since the first has nothing i need now */ 
while((input = fgetc(file)) != EOF && input != '\n') {} 

/* read 4 lines every loop from the second line to the EOF */ 
while((input = fgetc(file)) != EOF) 
{ 
    /* rewind the pointer to the previous character (the one I read to see if the file ended) */ 
    if(fseek(file, -1, SEEK_CUR) == -1) logMmboxd("failed seeking USERS\n", 1); 

    /* expand the array of 1 user */ 
    users = realloc(users, n+1); 
    n++;  

    for(k=0; (input=fgetc(file)) != '\n' && input != EOF; k++) users[n-1].username[k] = input; 
    users[n-1].username[k+1] = '\0';  

    for(k=0; (input=fgetc(file)) != '\n' && input != EOF; k++) users[n-1].password[k] = input; 
    users[n-1].password[k+1] = '\0';  

    for(k=0; (input=fgetc(file)) != '\n' && input != EOF; k++) users[n-1].token[k] = input; 
    users[n-1].token[k+1] = '\0'; 

    users[n-1].logged_pid = 0; 

    for(k=0; (input=fgetc(file)) != '\n' && input != EOF; k++) line[k] = input; 
    line[k+1] = '\0'; 
    users[n-1].total_space = atoi(line);  

    users[n-1].used_space = usedSpace(users[n-1].username); 
} 

回答

1

此代碼:

/* expand the array of 1 user */ 
users = realloc(users, n+1); 

個字節,而不是一個User擴展users

+0

大聲笑。謝謝... users = realloc(users,sizeof(User)*(n + 1))。 – 2011-04-25 18:44:33

1
char input; 

應該是:

int input; 

否則EOF可能不被正確地檢測。每當我看到realloc()的呼叫,我總是不寒而慄。

+0

輸入是經常用fgetc讀取的字符,爲什麼它應該是int? – 2011-04-25 18:39:14

+0

@ hysoka44因爲fgetc()返回一個int。 – 2011-04-25 18:40:33

+0

你的權利,其實fgetc返回一個int:我正在修復它 – 2011-04-25 18:41:10