c - 二维数组分配函数中的 Malloc 调用有时会崩溃

标签 c arrays malloc 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_fvt_ofvb_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/

相关文章:

c - 如何从 Win32 API 获取打印机制造商和型号?

html - 我们可以使用正则表达式使用 libxml2 查找具有特定属性值的所有节点吗?

c - 在C中插入数组结构(字典)

c - 编译器 gcc 错误 : undefined reference to `main'

c - 传递给函数时数组的大小

jquery - 每 10 秒轮换一次背景图像 url

c - 我的 C 代码中出现奇怪的结果

c - 带有结构的 Malloc

c++ - 在cuda中有更好/更清洁/更优雅的malloc和free方式吗?

c - 我不断收到段错误