c - 读入缓冲区时内存泄漏

标签 c memory valgrind memory-leaks

这是一个简单的程序,它将文件“hello.txt”读入一个动态分配的缓冲区,最初大小为 10(当它被填满时大小加倍)

运行 valgrind 时,似乎有内存泄漏,但我不确定问题出在哪里。我在使用后释放了缓冲区的内存。

错误似乎是“条件跳转或移动取决于未初始化的值”

谁能帮忙判断是否存在内存泄漏?如果不是,问题是什么?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFERSIZE 10

int main(int argc, char const *argv[])
{
    FILE *source;
    source = fopen("hello.txt","r");
    char *buffer = (char *)malloc(BUFFERSIZE);

    int current_size = BUFFERSIZE;
    int len = 0;
    char c;
    while((c = fgetc(source)) != EOF)
    {
        if(len == current_size-1)
        {
            current_size *= 2;
            buffer = (char *)realloc(buffer,current_size);
        }
        buffer[len] = c;
        len++;
    }                                                                
    printf("%s",buffer);
    free(buffer);

    return 0;
}

最佳答案

The error appears to be "Conditional jump or move depends on uninitialised value(s)"

那你为什么要询问内存泄漏?此错误的来源很可能是对 printf("%s", buffer) 的调用,其中 buffer 不是有效字符串(没有 '\0' 终止符)。

您的代码的另一个问题是您将 fgetc 的返回值分配给 char。您应该将 char c 更改为 int c

关于c - 读入缓冲区时内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14508693/

相关文章:

c - "Expected identifier or ' ( ' before int"尝试同时使用定义和函数时出错

c++ - 内存动态分配 C++ 性能改进

c 字符串比较 vs 哈希比较

c - 如何识别 C 中重新定义的宏?

c - MPI 中的内存问题

python - Python:无法复制内存使用情况的测试

c - 从结构体指针数组中删除元素

mysql - Valgrind 可能丢失 - MYSQL

c - 仅使用 valgrind 分析部分函数和子函数

c - C 中的合并排序不起作用