我正在學習C語言,並且在查找如何釋放我的malloc()時遇到問題。簡單程序的內存泄漏,我怎樣才能免費分配?
該程序運行正常..但IM使用Valgrind的,它是未來與8個allocs和5周的FreeS。我需要能夠釋放3個。我評論說我相信我不是免費的,但我不確定是否有解決方案。
有沒有一種方法,我可以釋放這些allocs,或者我需要考慮重新書寫標記生成器()?
下面是代碼整個文件。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char *substr(const char *s, int from, int nchars) {
char *result = (char *) malloc((nchars * sizeof(char))+1);
strncpy(result, s+from, nchars);
return result;
}
/**
Extracts white-space separated tokens from s.
@param s A string containing 0 or more tokens.
@param ntokens The number of tokens found in s.
@return A pointer to a list of tokens. The list and tokens must be freed
by the caller.
*/
char **tokenize(const char *s, int *ntokens) {
int fromIndex = 0;
int toIndex = 0;
char **list;
int finalCount = *ntokens;
int count = 0;
list = malloc(*ntokens * sizeof(char*));
while (count < finalCount) {
char *m = strchr(s,' ');
toIndex = m - s;
if(toIndex >= 0) {
list[count] = substr(s,fromIndex,toIndex); // This substr() gets free'ed from main()
s = substr(s, toIndex+1, strlen(s)); // I believe This is where I am making extra mallocs that are not being freed
count++;
} else {
list[count] = substr(s,fromIndex,strlen(s)); // This substr() gets free'ed from main()
count++;
}
}
return list;
}
int main(int argc, char **argv) {
char **list;
char *string = "terrific radiant humble pig";
int count = 4; // Hard-Coded
list = tokenize(string, &count);
for (int i=0;i<count;i++) {
printf("list[%d] = %s\n", i, list[i]);
}
// Free mallocs()'s
for (int i=0;i<count;i++) {
free(list[i]);
}
// Free List
free(list);
return 0;
}
Wierd,它不給我任何warrnings – John 2013-03-02 02:26:09
你正在編譯-Wall和-Werror? – Asblarf 2013-03-02 02:27:11
關閉主題,但'count ++'不一定在'if/else'中,因爲在這兩種情況下你都會增加計數。 – Asblarf 2013-03-02 02:31:22