【问题标题】:Will there be any memory leak if I use malloc in this context如果我在这种情况下使用 malloc 会不会有任何内存泄漏
【发布时间】: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 memory-leaks


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    只要您使用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数组中的same指针槽,在这种情况下会泄漏内存(因为你没有@987654326 @之前分配的指针)。

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

    【讨论】:

    • char** words = (char**) malloc(num_words * sizeof(char*)); words[word_being_allocated] = (char*) malloc(size) 这部分代码我很担心。
    • 我已经更新了部分代码。如果你能看一下,我将不胜感激
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 2011-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多