在读取多个文件时,我的代码的某些部分有问题。这是其中的大部分内容:
char *a;
int ch;
char *line = NULL;
char *prev_line[999];
size_t len = 0;
size_t read;
if (argc > 1)
{
int i = 1;
FILE *fp;
while (i < argc)
{
a = malloc (MAX_NAME_SZ * sizeof (char));
fp = fopen (argv[i], "r");
if (fp == NULL)
{
/*Error statement in case an file doesn't exist */
}
else
{
while ((read = getline(&line, &len, fp)) != -1) {
if (strncmp(line, prev_line, read) != 0) {
strncat(a, line, read);
strncpy(prev_line, line, read);
}
}
free(line);
fclose (fp);
changeCase (a);
printf ("\n");
}
i++;
}
}
else
{
a = malloc (MAX_NAME_SZ * sizeof (char));
fgets (a, MAX_NAME_SZ, stdin);
changeCase (a);
printf ("\n");
}
}
但我的问题包括这部分。
while ((read = getline(&line, &len, fp)) != -1) {
if (strncmp(line, prev_line, read) != 0) {
strncat(a, line, read);
strncpy(prev_line, line, read);
}
}
free(line);
这部分代码只读取前一行独有的行。但是,当我有多个参数并且此代码经过两次时,我会得到一个双重释放或损坏错误,我认为这是因为 free(line) 执行了两次。
代码中是否还有其他地方我应该移动它,或者我可以用它替换它?