編輯內存空間:這個問題是不是我還以爲是,讀我(長)問題將免去你前一段時間檢查答案。正確釋放其他功能malloced
我一直valgrinding學校我的小C++項目(基本上是語言檢測器),但有一組指針我仍然有根據的valgrind的問題。我認爲這個問題很經典,可以在下面繼續:當我(我想)沒有選擇時,我應該如何釋放一個變量,然後在另一個函數中插入?
這裏有兩個功能,這使我這個問題的相關部分。基本上,get_modeles_names
從我的「集合」文件中收集其中包含正確子字符串的文件名;那麼det_langue
正在處理它們。 這裏是get_modeles_names:
void get_modeles_names(int mode, char ** modeles)
{
FILE * collection = get_collection_file();
int i = 0;
char * line = NULL;
size_t size = 0;
while (getline(&line, &size, collection) != -1) {
if (strstr(line, entete)) {
modeles[i] = (char*) malloc(strlen(line) * sizeof (char));
modeles[i] = line;
modeles[i][strlen(modeles[i]) - 1] = '\0';
//replaces the final '\n' by '\0'
i++;
line = NULL;
}
}
if (line)
free(line);
fclose(collection);
}
這裏是det_langue:
void det_langue(char * w)
{
int nb_modele = nb_modeles();
char ** modeles = (char **) malloc(nb_modele * sizeof (char *));
get_modeles_names(mode, modeles);
double * resultats = (double *) malloc(nb_modele * sizeof (double));
int i;
for (i = 0; i < nb_modele; i++) {
resultats[i] = calculate_result (w, modeles[i]);
}
}
for (i = 0; i < nb_modele; i++) {
free(modeles[i]);
}
free(modeles);
free(resultats);
}
正如你所看到的,我的malloc我的字符** MODELES在det_langue到合適的大小(我相信在nb_modeles功能工作罰款),然後我malloc每個元素的get_modeles_names中的模型;但是因爲我以後需要處理它們,所以我無法釋放它們(或者不知道如何)在哪裏放置它們,之後我會釋放它們,直到det_langue結束。我會認爲這還好吧,但這裏的valgrind --leak-check=full ./projet -d pomme -m 1
==30547== Command: ./projet -d pomme -m 1
==30547==
pomme -> french
==30547==
==30547== HEAP SUMMARY:
==30547== in use at exit: 113 bytes in 4 blocks
==30547== total heap usage: 40 allocs, 36 frees, 30,906 bytes allocated
==30547==
==30547== 113 bytes in 4 blocks are definitely lost in loss record 1 of 1
==30547== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==30547== by 0x40163E: get_modeles_names (gestion_collection_modeles.c:120)
==30547== by 0x401919: det_langue (det_langue.c:12)
==30547== by 0x40189E: main (Main.c:76)
==30547==
==30547== LEAK SUMMARY:
==30547== definitely lost: 113 bytes in 4 blocks
==30547== indirectly lost: 0 bytes in 0 blocks
==30547== possibly lost: 0 bytes in 0 blocks
==30547== still reachable: 0 bytes in 0 blocks
==30547== suppressed: 0 bytes in 0 blocks
==30547==
==30547== For counts of detected and suppressed errors, rerun with: -v
==30547== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
輸出120線是get_modeles_names,它是:modeles[i] = (char*) malloc(strlen(line) * sizeof (char));
此外,MODELES的大小爲4,這也解釋了40個allocs但只有36的FreeS。 另外,如果我在get_modeles_names
函數中發瘋,並且只是自由模式,我的程序顯然是seg_faults,因爲我應該處理的數據不再存在。
我GOOGLE了四周,卻找不到已經問這會回答我的任何問題....任何想法?
編輯:mem_leak在溶液中所描述的,但只要它的解決還有另一種:線泄漏,這是由在while循環內移動
if(line)
free(line);
解決。
我不認爲有人會在你的代碼中查找內存泄漏,請將此作爲建議:「分配內存的人必須清除它」。即如果你在'func foo'中分配了一個內存,一定要在'func foo'中釋放它,如果它不再需要的話。 –
我的問題是:如果我在func foo中分配的內存仍然需要,我的行爲應該是什麼? –
文檔和清晰的界面。如果你有'get_modeles_names',那麼你應該提供'free_modeles_names'函數。 – StoryTeller