c - "test.exe encountered a breakpoint"

标签 c visual-studio-2015

我正在编写一个 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 终止输入字符串的行能够溢出您calloced 或realloced 的缓冲区。当您释放该缓冲区时,这有可能破坏您的堆。

分配内存时不要忘记在字符串末尾为空字符留出空间。

以空字符结尾的字符串就像迪斯科舞厅。四十年后他们仍然很烂。

关于c - "test.exe encountered a breakpoint",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34445799/

相关文章:

c - 如何在我的 write() 超时时破坏性地关闭套接字?

c - Linux fork : pid reuse

c# - Visual Studio 2015 社区 - 调试器表现奇怪

计算周薪和加类费的C程序不起作用?调试

c++ - 针对推送优化的线程安全 C/C++ 队列

c - 预期的标识符什么的?

tfs - 如何分支我的 Visual Studio Online (TFS) 解决方案?

c++ - 获取 Visual Studio 使用的 C++ 标准版本

visual-studio - Visual Studio (2012, 2015) 重建项目,尽管没有任何改变

entity-framework - 我们如何从 Telerik Open Access 切换到其他任何东西?