"test.exe encountered a breakpoint"

I am writing a UNIX pasteclone. However, I continue to receive “meet breakpoint” messages, but V.S. won't tell me in which line this 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 set breakpoints and saw that this is a statement free(line)in horzmerge. But sometimes the program works fine. This is sometimes not the case. Sometimes I get a bunch of damaged ones in getline. I have been working on this code for a week but cannot find any errors.

+4
source share
1 answer

, , , , calloc ed realloc ed. , free .

.

. .

+1

Source: https://habr.com/ru/post/1621550/


All Articles