【发布时间】:2013-07-29 07:12:24
【问题描述】:
我正在使用指向 1D 数组的指针数组来模拟 2d 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 的第一个 malloc 处崩溃>。当我切换 readFeatureVectors 调用的顺序时,程序在 t_fv(不是 t_ofv)的第一个 malloc 处崩溃。
我还开发了该函数的 realloc 和 dealloc 版本,但它们在代码中此时并未发挥作用。
我知道我应该开始使用调试器或内存检查工具,但我无法让它与 Eclipse Juno 一起使用。我可能会迁移到 Ubuntu 并尝试使用 valgrind,但如果可能的话,我希望现在避免使用它。
【问题讨论】:
-
您检查过
rows和columns的值是否合理? -
@DrewMcGowen:是的,它们与我正在阅读的文件相匹配。
-
听起来会发生这种情况,因为 'rows' 有一些奇怪的值。您能否在 malloc 之前验证该值是否正确?我还假设 t_rows、b_rows 等也是全局的。我在想它们上面的一些数组正在被覆盖并破坏它们。 (相当投机......我知道)。
-
为什么t_fv需要**?看起来你正在做的事情有点矫枉过正。