这是一个简单的程序,它将文件“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/