c - 读取数百行后程序中断

标签 c string malloc fgets realloc

我创建了一个扫描函数,它本质上只是将文件的行扫描到一个名为 bufferchar * 中。然而,在读取了几百行之后,程序就停止工作了。我刚刚收到一个程序已停止工作的弹出窗口。假设我在内存分配上做错了什么,但我不确定是什么。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *scan_file(FILE *fp);

#define MAX_LINE                200


int main(void) {
    FILE *fp = fopen("test.txt", "r");
    char *contents = scan_file(fp);
    printf("%s\n", contents);
    return 0;
}
// Scan in file into a buffer. Returns a malloc-ed string
char *scan_file(FILE *fp) {

    int buf_len = 1;
    int contents_len = buf_len;

    char *buffer = malloc(sizeof(char) * (MAX_LINE + 1));
    char *contents = malloc(sizeof(char) * (buf_len + 1));
    strcpy(contents, "\0");

    while (fgets(buffer, MAX_LINE, fp) != NULL) {
        buf_len = strlen(buffer);
        contents_len += buf_len;
        realloc(contents ,contents_len);
        strcat(contents, buffer);
        strcpy(buffer, "\0");
    }

    free(buffer);
    return contents;
}

最佳答案

代码无法使用返回值形式realloc()

分配大小减少 1。

重复 strcat() 会导致缓慢的 (n*n) 解决方案。

考虑使用 size_t 来确定数组大小,而不是使用 int

不要调用变量...len,而是考虑...size来确认最后一个空字符的存在字符串

char *scan_file(FILE *fp) {
    // int buf_len = 1;
    size_t buf_size = 1;

    // int contents_len = buf_len;
    size_t contents_size = buf_size;

    // char *buffer = malloc(sizeof(char) * (MAX_LINE + 1));
    // fgets(..., MAX_LINE, ...) will only read up to MAX_LINE - 1 characters.
    char *buffer = malloc(MAX_LINE);

    char *contents = malloc(buf_size + 1u);
    if (buffer == NULL || contents == NULL) {
      fprintf(stderr, "Out of memory\n");
      return EXIT_FAILURE;
    }

    // strcpy(contents, "\0");
    contents[0] = '\0';

    while (fgets(buffer, MAX_LINE, fp) != NULL) {
        // buf_len = strlen(buffer);
        buf_size = strlen(buffer) + 1u;

        // contents_len += buf_len;

        // realloc(contents ,contents_len);
        void *p = realloc(contents ,contents_size + buf_size);
        if (p == NULL) {
          fprintf(stderr, "Out of memory\n");
          return EXIT_FAILURE;
        }
        contents = p;

        // strcat(contents, buffer);
        strcpy(contents + contents_size, buffer);

        // now add
        contents_size += buf_size;

        // Code here not truly needed, yet helps in debugging.
        // strcpy(buffer, "\0");
        buffer[0] = '\0';
    }

    free(buffer);
    return contents;
}

关于c - 读取数百行后程序中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53310587/

相关文章:

c - 同一程序在一个编译器而不是另一个编译器中给出编译器错误

c++ - 为什么 std::runtime_error::what() 返回 const char* 而不是 std::string const&

java - 检查字符串、正则表达式问题?

c - 增加堆缓冲区大小的最佳方法

c - _int_malloc 导致段错误的 malloc

c - 文件无法识别 : File format not recognized

c++ - 如何将 Linux 可执行文件添加到 .gitignore?

C 和 doxygen - 删除变量文档的重复项

c++ - 给定数字 block C++ 中的最大可能数

c - 在 C99 中使用 free() 之后的指针?