Valgrind 在这段代码中检测到大小为 1 的无效写入。 在此,我读取了一个文件,其中第一行是我不需要的内容,以下行定义了我需要放入此结构中的 3 个字符串和 1 个 int (total_space):
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);
}
最佳答案
这段代码:
/* expand the array of 1 user */
users = realloc(users, n+1);
将 users
扩展一个字节,而不是一个 User
。
关于c - valgrind 在这段代码上出现无效写入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5781711/