我正在编写一个UNIX粘贴克隆.但是我不断收到“遇到断点”的消息,但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中的自由(行)语句.但有时程序运行正常.有时却没有.有时我会在getline中收到“堆损坏”.我已经在这个代码上工作了一个星期,仍然找不到bug.
最佳答案 它看起来像你在null处终止输入字符串的行能够超越你calloced或realloced的缓冲区.当你释放缓冲区时,这有可能破坏你的堆.
当您分配内存时,别忘了为字符串末尾的空字符留出空间.
空终止的字符串就像迪斯科.四十年后他们仍然吮吸.