如果我在此上下文中使用malloc,是否会有任何内存泄漏

时间:2016-10-07 15:14:14

标签: c memory-leaks

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两次。我的问题是因为我正在为**单词分配内存,当我写单词时[word_being_allocated] =(char *)malloc(size);是不是再次分配。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

对于使用free()分配的每个内存块,只要正确malloc(),就没有内存泄漏。

编辑在此代码中:

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);

您似乎没有更新word_being_allocated,因此您可能会覆盖words数组中的相同指针位置,并且在这种情况下会泄漏内存(因为您不会't free以前分配的指针。)

正确更新word_being_allocated后,请确保溢出words指针数组的边界。