Reputation: 11237
I am writing a UNIX paste
clone. However I keep getting "encountered a breakpoint" messages, but VS won't tell me on what line it happened.
#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;
}
I placed breakpoints, and saw that it was the free(line)
statement in horzmerge
. But sometimes the program runs fine. Sometimes it doesn't. Sometimes I get a "Heap corrupted" in getline
. I've been working on this code for a week, still can't find the bug(s).
Upvotes: 4
Views: 73
Reputation: 108641
It looks to me like the line where you null-terminate the input string is capable of overrunning the buffer you calloc
ed or realloc
ed. That has the potential of corrupting your heap when you free
that buffer.
Dont't forget to leave room for the null character at the end of the string when you allocate memory.
Null-terminated strings are like disco. They still suck forty years later.
Upvotes: 1