我正在構建一個數組,我希望它是一個固定的大小,因此,當我在文件中讀取它只存儲最後10個命令。該文件似乎正確讀取,它看起來是正確的,當我打印它,但由於某種原因,我的記憶沒有得到釋放。 MAX設置爲1000 並且historySize從用戶讀取更早。我在我的代碼上運行valgrind,當這些函數的調用被註釋掉時,我沒有任何泄漏。泄漏內存和可能的malloc錯誤
我有一個char **歷史在我的#includes
這裏是我的代碼
void setupHistoryFile()
{
char string[MAX];
FILE *fp;
int len;
int pos = 0;
fp = fopen(".ush_history","r");
if(fp == NULL)
{
//create the file
fp = fopen(".ush_history","w");
}
else
{
history = (char**)malloc(historySize * sizeof(char*));//setup history file
fgets(string,MAX,fp);
len = strlen(string);
if(string[len-1]=='\n')
string[len-1]='\0';
while(!feof(fp))
{
if(history[pos] != NULL)
{
free(history[pos]);
history[pos]=NULL;
}
history[pos] = (char*)malloc((strlen(string)+1) * sizeof(char));
//printf("Should be copying %s\n",string);
strcpy(history[pos], string);
pos++;
pos = pos % historySize;
fgets(string,MAX,fp);
len = strlen(string);
if(string[len-1]=='\n')
string[len-1]='\0';
}
}
fclose(fp);
}
我確實有這種清潔史上的一個功能,它看起來像這樣
void cleanHistory()
{
int i;
if(history != NULL)
{
for(i=0;i<historySize;i++)
{
free(history[i]);
history[i] = NULL;
}
free(history);
history = NULL;
}
}
你確定你的釋放函數'cleanHistory()'在你分配內存的指針數組上調用嗎?你可以在'cleanHistory()'中放置斷點,並檢查這個函數是否被調用。 – 2012-01-31 07:27:54
我在#includes下有一個char **歷史記錄,我可以在調用函數後在main中打印它的內容。 – samack 2012-01-31 07:30:21
valgrind ........ – 2012-01-31 07:32:07