gpt4 book ai didi

c - 如果我在这种情况下使用 malloc 会出现内存泄漏吗

转载 作者:行者123 更新时间:2023-11-30 20:35:17 24 4
gpt4 key购买 nike

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[word_being_allocated] = (char*) malloc(size); 时,我已经为 **words 分配了内存。不是又分配了么。

最佳答案

据我们所知,只要您不丢弃任何 malloc()ed 内存,您提供的代码就很好。所以至少你有机会不泄漏。您是否确实如此取决于您在处理数据后如何继续。

关于c - 如果我在这种情况下使用 malloc 会出现内存泄漏吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39920607/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com