【发布时间】: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 和 3frees。对我来说,这立即意味着一个逻辑错误。虽然不一定是手头的问题,但我建议“对称”实现函数buildOptions和freeOptions。 -
也请read about how to ask good questions,以及关于the XY problem。代码试图做什么?您尝试解决的实际问题是什么?
-
@barakmanos 在
main函数中也有一个calloc。 -
最后,访问未分配给您或您的程序的内存(例如在释放它之后)会导致未定义的行为。不要这样做。
标签: c memory memory-management out-of-memory heap-memory