我正在编写一个 UNIX paste
克隆。然而,我不断收到“遇到断点”消息,但 VS 不会告诉我发生在哪一行。
#include <stdio.h>
#include <stdlib.h>
#define INITALLOC 16
#define STEP 8
int main(int argc, char *argv[])
{
if (horzmerge(argc - 1, argv + 1) == 0) {
perror("horzmerge");
return EXIT_FAILURE;
}
getchar();
return EXIT_SUCCESS;
}
int horzmerge(int nfiles, const char **filenames)
{
FILE **files;
char *line;
int i;
if ((files = malloc(nfiles * sizeof (FILE *))) == NULL)
return 0;
for (i = 0; i < nfiles; ++i)
if ((files[i] = fopen(filenames[i], "r")) == NULL)
return 0;
do {
for (i = 0; i < nfiles; ++i) {
if (getline(files[i], &line) == 0)
return 0;
fprintf(stdout, "%s", line);
free(line);
}
putchar('\n');
} while (!feof(files[0])); /* we can still get another line */
for (i = 0; i < nfiles; ++i)
fclose(files[i]);
free(files);
return 1;
}
int getline(FILE *fp, char **dynline)
{
size_t nalloced = INITALLOC;
int c, i;
if ((*dynline = calloc(INITALLOC, sizeof(char))) == NULL)
return 0;
for (i = 0; (c = getc(fp)) != EOF && c != '\n'; ++i) {
if (i == nalloced)
if ((*dynline = realloc(*dynline, nalloced += STEP)) == NULL)
return 0;
(*dynline)[i] = c;
}
(*dynline)[i] = '\0';
if (c == EOF)
return EOF;
return i;
}
我下了断点,看到是horzmerge
中的free(line)
语句。但有时程序运行良好。有时它没有。有时我在 getline
中收到“堆已损坏”。我已经在这段代码上工作了一个星期,仍然找不到错误。
最佳答案
在我看来,您以 null 终止输入字符串的行能够溢出您calloc
ed 或realloc
ed 的缓冲区。当您释放
该缓冲区时,这有可能破坏您的堆。
分配内存时不要忘记在字符串末尾为空字符留出空间。
以空字符结尾的字符串就像迪斯科舞厅。四十年后他们仍然很烂。
关于c - "test.exe encountered a breakpoint",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34445799/