我有一個用 C 語言撰寫的守護行程,它每秒INTERVAL
逐行讀取一個檔案,如果符合條件,則在每一行上做一些作業。我無法打開檔案,因為該檔案正在被另一個 API 訪問和修改,所以這是顯示問題的代碼片段:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#define INTERVAL 5
int main(int argc, char *argv[])
{
size_t len = 100;
FILE *fp;
char *line = NULL;
line = malloc(len * sizeof(char));
size_t read;
int iteration = 1;
while (1)
{
printf("iteration %d\n", iteration );
fp = fopen("input.txt", "r ");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1)
{
printf("line is: %s\n", line);
// Do some more work with the data.
// If the password has expired remove it from the file.
}
fclose(fp);
if (line)
{
free(line);
}
sleep(INTERVAL);
}
}
運行此代碼時,結果如下:
iteration 1
line is: 1656070481 qwerty12345
line is: 1656070482 qwerty
iteration 2
line is: 1656070481 qwerty12345
line is: 1656070482 qwerty
daemon(37502,0x1027e4580) malloc: *** error for object 0x600003ca8000: pointer being freed was not allocated
daemon(37502,0x1027e4580) malloc: *** set a breakpoint in malloc_error_break to debug
zsh: abort ./daemon
所以問題出在這一行:
if (line)
{
free(line);
}
看起來指標以某種方式在while回圈內的某處被釋放。因此,為了解決這個問題,我必須malloc
在回圈開始時呼叫該函式以在while(1)
每次迭代時重新分配記憶體,如下所示:
while (1)
{
printf("iteration %d\n", iteration );
line = malloc(len * sizeof(char));
這解決了這個問題,但我想首先了解為什么會發生這個問題。為什么指標在第二次迭代后被釋放?
uj5u.com熱心網友回復:
有一個用 C 撰寫的守護行程
然后呼叫daemon(3)。
所以問題出在這一行:
if (line){ free(line); }
是的。所以你需要清除line
和編碼
if (line) {
free(line);
line = NULL;
len = 0;
}
在下一個回圈中,line
將是NULL
并且您不會(錯誤地)free
它兩次。
(我不會在回圈內free
打擾,但這只是我的意見)
當然,在getline
你要 allocateline
之前,so before
while ((read = getline(&line, &len, fp)) != -1)
代碼:
if (!line) {
line = malloc(100);
if (line)
len = 100;
};
考慮使用valgrind,在某些情況下使用Boehm 保守 GC(或我的舊Qish GC ,可在此處下載)。然后,您可能不得不避免getline
并使用更簡單和更低級別的替代方案(例如read(2)或簡單地fgetc(3) ...)
閱讀GC 手冊。
也許在您的源代碼上使用Frama-C 。
(也可以考慮使用Rust或Go或 C 或Ocaml或 Common Lisp/ SBCL來完全重新編碼你的守護行程)
在 Linux 上,另請參見inotify(7)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/496569.html
上一篇:C參考傳遞