【问题标题】:Am I freeing memory properly in this C program?我是否在这个 C 程序中正确释放内存?
【发布时间】:2015-06-18 04:42:55
【问题描述】:

我正在编写一个从用户那里读取多行输入的小程序:

#include <stdio.h>
#include <stdlib.h>

#define MAXINPUT 256
#define MAXLINES 32

/* Reads at most maxLines inputs from stdin. Returns number of lines. */
int readlines(char** buffer, int maxLines, size_t maxInput);
/* Gets input from stdin with maxInput as the limit. Returns size of string. Terminates at newline. */
int getstdline(char* buffer, int maxInput);

int main(int argc, char** argv) {
    char** buffer = malloc((sizeof buffer[0]) * MAXLINES);
    int numlines = readlines(buffer, MAXLINES, MAXINPUT);

    /* free memory that was allocated for each str */
    for(int i = 0; i < numlines; ++i) {
        free(*(buffer++));
    }
    /* free memory that was allocated to hold all the strings */
    free(buffer);
}

int readlines(char** buffer, int maxLines, size_t maxInput) {
    int linecount = 0;

    while(maxLines--) {
        char* tmp = malloc(maxInput);
        /* if empty string, exit loop */
        if(getstdline(tmp, maxInput) <= 0) {
            free(tmp);
            break;
        }

        *buffer = tmp;
        ++linecount;
        ++buffer;

    }
    return linecount;
}

我的问题是关于在readlines(char**,int,size_t) 中对malloc() 的调用。我显然不能free() 函数内的内存,所以要在程序结束时释放它,我尝试循环遍历char* 的数组并单独释放它们。然后我还在main() 中释放char** buffer,因为它也是使用malloc() 分配的。

遍历它们中的每一个都会给我错误:

object was probably modified after being freed.

最后释放char** buffer工作正常

所以似乎有一个我不太了解的动态内存概念。为什么会发生这种情况?在这个特定程序中处理内存的正确方法是什么?

【问题讨论】:

  • char** buffer = malloc(MAXLINES); 应该是char** buffer = malloc(MAXLINES * sizeof buffer[0]);。可怜的malloc() 看不懂你的心思。
  • @TheParamagneticCroissant 哎呀!修好了。
  • @TheParamagneticCroissant 我猜这不应该是解决办法。问题依然存在。
  • 这是问题之一。 “修复”正在这样做答案建议。这也是一个问题,没有我的评论也无法正常工作。

标签: c malloc free dynamic-memory-allocation


【解决方案1】:

问题是您正在通过运行buffer++ 修改缓冲区指针,因此当您调用free(buffer) 时,您传入了错误的指针。您可以重写循环以不修改该指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多