【发布时间】:2016-10-07 15:14:14
【问题描述】:
int num_words = 0;
while ((c = fgetc(in_fp)) != EOF) {
if (c == 32 || c == 10 || c == 13 || c == 46) {
//32 is Space, 10 is LF, 13 is CR, 46 is period
//todo: Add other kinds of punctuation
num_words = num_words + 1;
}
}
char** words = (char**) malloc(num_words * sizeof(char*));
if (words == NULL) {
printf("Memory allocation failed\n");
return 1; //abort program
}
//Reset the input file pointer to the start of the file
rewind(in_fp);
//Allocate enough space for each word
int word_being_allocated = 0;
int word_size = 0;
int size;
while ((c = fgetc(in_fp)) != EOF) {
if (c == 32 || c == 10 || c == 13 || c == 46) {
//32 is Space, 10 is LF, 13 is CR, 46 is period
size = (word_size + 1) * sizeof(char);
words[word_being_allocated] = (char*) malloc(size);
if (words[word_being_allocated] == NULL) {
printf("Memory allocation failed\n");
return 1;
}
word_being_allocated = word_being_allocated + 1;
word_size = 0;
continue;
}
word_size = word_size + 1;
}
for (int i = 0; i < num_words; i++) {
free(words[i]);
}
free(words);
会不会有内存泄漏,因为我用了两次malloc。我的问题是因为我已经为 **words 分配内存,当我写 words[word_being_allocated] = (char*) malloc(size);是不是又分配了。
【问题讨论】:
-
你用哪种语言写作? C++ 还是 C?
-
这不是您的真实代码,也不是minimal reproducible example。例如你没有关闭你的
while或if.... -
这不是完整的代码。我只是添加了部分代码。要不要我放完整的代码?
-
不,我希望您按照帮助中心“如何提问”部分中的说明发布您的 minimal reproducible example。
标签: c memory-leaks