[英]Memory leak / not properly freeing. How to fix?
我正在將輸入部分讀入 function 中的緩沖區,然后在 main() 中釋放它,但它似乎不起作用。 我的代碼:
char *save_to_buff()
{
int fd = 0; // set read() to read from STDIN_FILENO, because it's number is 0
const size_t read_size = 100; // set chunk size
size_t size = read_size;
char *buff = malloc(size+1);
size_t offset = 0;
size_t res = 0;
while((res = read(fd, buff + offset, read_size)) > 0) // partial read from stdin and save to buff
{
if(res == -1) // check for read errors
{
read_error();
free(buff);
return NULL;
}
offset += res;
if (offset + read_size > size)
{
size *= 2;
buff = realloc(buff, size+1);
}
buff[offset] = '\0';
}
return buff;
}
主要的:
char *buff = save_to_buff();
// do sth
free(buff);
編輯:剛剛嘗試了 1 字節讀取而不是部分讀取,並且沒有 memory 泄漏。
當您讀取整個文件一次時,讀取指針位於 EOF,如果您再次讀取,就像在您的代碼中一樣, read()
將根據this返回 0。 這將退出您的循環而不釋放 memory。
此外,取決於您正在閱讀的文件類型:不支持查找的文件 - 例如終端 - 始終從當前 position 讀取。 與此類文件關聯的文件偏移量的值未定義
您沒有發布main()
function 的完整代碼,可能有一些我們看不到的可疑內容。
function save_to_buff
有一些問題:
stdin
在啟動時已經位於文件末尾,它將返回一個指向未初始化的101
字節塊的指針。 它應該返回 null 指針或指向空字符串的指針。只要您不修改// do sth
部分中的buff
,代碼片段中的調用順序似乎很好。
這是修改后的版本:
#include <stdio.h>
#include <unistd.h>
char *save_to_buff() {
int fd = 0; // set read() to read from STDIN_FILENO
const size_t read_size = 100; // set chunk size
size_t size = read_size;
size_t offset = 0;
size_t res = 0;
char *buff = malloc(size + 1);
if (buff == NULL)
return NULL;
*buff = '\0';
while ((res = read(fd, buff + offset, read_size)) != 0) {
// partial read from stdin and save to buff
if (res == (size_t)-1) { // check for read errors
read_error();
free(buff);
return NULL;
}
offset += res;
buff[offset] = '\0';
if (offset + read_size > size) {
char *buff0;
size *= 2;
buff = realloc(buff0 = buff, size + 1);
if (buff == NULL) {
free(buff0);
return NULL;
}
}
}
return buff;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.