我正在使用指向一维数组的指针数组来模拟二维 int 数组。当从文件中读取数据时,大小是动态的,因此我创建了一个动态分配函数(alloc2DArrInt)。它一直运行良好,直到我开始使用新数据测试我的程序,现在第一个 malloc 有时会崩溃(段错误?)。这是代码的相关(我希望)部分:
int** t_fv = NULL; // these are global
int** t_ofv = NULL;
int** b_fv = NULL;
int** b_ofv = NULL;
// assume these 2 lines are in main:
if (readFeatureVectors(&t_fv, &t_ofv, targetFilename, &trows, &tcolumns) < 0) { }
if (readFeatureVectors(&b_fv, &b_ofv, backgroundFilename, &brows, &bcolumns) < 0) { }
int readFeatureVectors(int*** fv, int*** ofv, char* fileName, int* rows, int* columns) {
// hidden code
alloc2DArrInt(fv, *rows, *columns); //&*fv
alloc2DArrInt(ofv, *rows, *columns);
// hidden code
}
void inline alloc2DArrInt(int*** array, int rows, int columns) {
int i;
*array = malloc(rows * sizeof(int*)); // sometimes crashes
if (*array != NULL ) {
for (i = 0; i < rows; i++) {
(*array)[i] = malloc(columns * sizeof(int));
if ((*array)[i] == NULL ) {
printf("Error: alloc2DArrInt - %d columns for row %d\n", columns, i);
exit(1);
}
}
} else {
printf("Error: alloc2DArrInt - rows\n");
exit(1);
}
}
t_fv、t_ofv 和 b_fv 的分配工作正常,但程序在第一次分配 b_ofv 时崩溃>。当我切换 readFeatureVectors 调用的顺序时,程序在 t_fv(不是 t_ofv)的第一个 malloc 处崩溃。
我还开发了该函数的 realloc 和 dealloc 版本,但此时它们在代码中尚未发挥作用。
我知道我应该开始使用调试器或内存检查工具,但我在使其与 Eclipse Juno 一起使用时遇到了困难。我可能会迁移到 Ubuntu 并尝试使用 valgrind,但如果可能的话,我希望暂时避免使用它。
最佳答案
malloc
行崩溃的唯一原因是堆数据结构损坏,或者array
指针无效。最可能的结果是 SIGSEGV。
否则,无论您传递给它什么参数,malloc都不会崩溃。最坏的情况下它会返回 NULL。
堆数据结构可能会由于缓冲区上溢/下溢而被损坏。使用 valgrind 检测该数组或无效的数组
指针条件。
关于c - 二维数组分配函数中的 Malloc 调用有时会崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17925007/