C - 为包含字符串的表动态分配内存

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

我尝试为包含字符串的表动态分配内存。
在我的例子中,我必须动态地使用它,因为我不知道程序将如何获得行和列。
这是我的两个函数的代码:
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;
}

最佳答案

freeOptions的声明改为

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

调用

 freeOptions(options, 5, 3);

并在 freeOptions 中调用 free()

  free(options[i][j]);

关于C - 为包含字符串的表动态分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36592260/

相关文章:

ios - 内存地址是否遵循 iOS 中的模式?

c - 为什么结构体数组的元素不交换?我正在尝试对学生结构数组进行排序。根据卷号

php - 带有命令行参数的 C 控制台应用程序中的井号 (#)

c - 将有理数表示为四舍五入的小数

C 指针数组、转换和/或内存

c++ - 为什么不分配内存就能正常工作

iphone - Instruments 是否显示 UIWebView 使用的内存?

python - 如何编写内存高效的 Python 程序?

linux - 限制Linux进程内存

c++ - Soft (not : weak) references in C++ - Is it possible? 有实现吗?