【问题标题】:C - Dynamic memory allocation for table that contains stringsC - 包含字符串的表的动态内存分配
【发布时间】:2016-08-04 04:28:54
【问题描述】:

我尝试为包含字符串的表动态分配内存。
就我而言,我必须动态使用它,因为我不知道程序将如何获取行和列。
这是我的两个功能的代码:
1.第一个是只为表分配内存。
2.第二个应该释放所有分配的内存。
3.在主函数中,我为字符串分配内存并复制预定义字符串的一部分(它是虚拟代码,仅作为示例)

结果是“运行时错误” 我在代码中做错了什么?

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

char *** buildOptions(int rows, int columns) {
    int i=0;
    printf("1...\n");
    char ***options = (char ***)malloc(rows * sizeof(char **));
    printf("2...\n");
    for(i=0; i<rows; i++) {
        printf("3...\n");
        options[i] = (char **)malloc(columns * sizeof(char *));
        printf("4...\n");
    }
    return options;
}

void freeOptions(char ****options, int rows, int columns) {
    int i, j;
    for(i=0; i<rows; i++) {
        for(j=0; j<columns; j++) {
            if(*options[i][j])
                free(*options[i][j]);
        }
        if(*options[i]) {
            free(*options[i]);
        }
    }
    free(*options);
}

int main(void) {
    int i, j, k;
    char * str = "123456789abcdefghjkl\0";
    char ***options = buildOptions(5, 3);
    printf("Starting...\n");
    for(i=0; i<5; i++) {
        for(j=0; j<3; j++) {
            options[i][j] = (char *)calloc((i+j+2)+1, sizeof(char));
            strncpy(options[i][j], str, i+j+2);
        }
    }

    for(i=0; i<5; i++) {
        for(j=0; j<3; j++) {
            printf(">>options[%d][%d]=%s<<\n", i,j, options[i][j]);
        }
    }

    freeOptions(&options, 5, 3);

    //here I want to check if the memory is freed
    for(i=0; i<5; i++) {
        for(j=0; j<3; j++) {
            printf(">>options[%d][%d]=%s<<\n", i,j, options[i][j]);
        }
    }


    return 0;
}

【问题讨论】:

  • 成为three-star programmer 并不是恭维。如果您需要类似的东西,您需要重新审视您的设计或研究不同的数据结构。
  • 我数了 2 mallocs 和 3 frees。对我来说,这立即意味着一个逻辑错误。虽然不一定是手头的问题,但我建议“对称”实现函数buildOptionsfreeOptions
  • 也请read about how to ask good questions,以及关于the XY problem。代码试图做什么?您尝试解决的实际问题是什么?
  • @barakmanos 在main 函数中也有一个calloc
  • 最后,访问未分配给您或您的程序的内存(例如在释放它之后)会导致未定义的行为。不要这样做。

标签: c memory memory-management out-of-memory heap-memory


【解决方案1】:

freeOptions的声明改为

void freeOptions(char ***options, int rows, int columns)

调用

 freeOptions(options, 5, 3);

以及在 freeOptions 中调用 free()

  free(options[i][j]);

【讨论】:

  • 它在 RedHat 上使用 gcc 对我有用。什么不适合你?
【解决方案2】:

分段错误的原因在于您如何访问freeOptions 中的数组:

*options[i][j]

等同于:

*(options[i][j])

bot options is the address of youroptionsinmain, so you should dereferenceoptions` 第一:

(*options)[i][j]

实际上不需要通过引用从main 传递char ***options,除非您打算在freeOptions 中将*options 设置为NULL。另一个迈克尔的回答中指出了实现freeOptions 的更好方法。

//here I want to check if the memory is freed

您无法确定free 是否通过访问现在无效的内存并导致未定义的行为成功。数据可能仍然存在,但它也可能包含垃圾。

【讨论】:

    猜你喜欢
    • 2021-11-30
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 2021-07-03
    • 2020-11-28
    相关资源
    最近更新 更多