Invalid write error from valgrind on this piece of code
Valgrind detect an invalid write of size 1 in this piece of code. In this, I read a file where the first line is something I don't need, and the following lines define 3 strings and 1 int (total_space) that I need to put in this struct:
typedef struct
{
char username[40];
char password[40];
char token[40];
pid_t logged_pid;
int total_space;
int used_space;
} User;
The file is this (each word on a new line, sorry but I still didn't understand how to format text and code):
pass
username1
password1
token1delczzzzozoc
4500000
username2
pasword2222
token2efwerfg
trg
1000000
Here is the code: valgrind yells only in the first 4 lines! And in the first one on the character "e": what's wrong with it?
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].logg开发者_JAVA百科ed_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);
}
This code:
/* expand the array of 1 user */
users = realloc(users, n+1);
Expands users
by one byte, not one User
.
char input;
should be:
int input;
otherwise EOF may not be detected correctly. And whenever I see a call to realloc()
I always shudder.
精彩评论