二维矩阵分配

问题描述 投票:0回答:1

我正在尝试创建一个二维矩阵,如下所示

#include <iostream>

int** createMatrix();

int main(int argc, char *argv[]) {
 using std::cout;
 int** m1=createMatrix();
 std::cout << sizeof m1;
}
int** createMatrix() {
int rows = 1000;
int cols = 1000;
int **matrix = (int **) malloc( rows * sizeof(int) );
 int *const row_ptr = (int *) malloc(sizeof(int) * cols * rows);
 for(int i=0;i< rows;i++){
   matrix[i] = &row_ptr[i * cols];
 }
 return matrix;
 }

当行和列值达到 100 * 100 值时,此代码可以正常工作;但是,当我将其增加到超过 100 * 100 时,我收到以下错误。

malloc(): corrupted top size

Aborted (core dumped)

有人能指出这个问题吗?

谢谢

c++ c malloc
1个回答
0
投票

这一行:

int **matrix = (int **) malloc( rows * sizeof(int) );

在 64 位平台上,

sizeof(int)
通常为 4,
sizeof(int*)
为 8。因此,您分配的内存是所需内存的一半。

在 32 位平台上,它会“恰好工作”,因为

sizeof(int) == sizeof(int*)
因此,你真的想要这个:

int **matrix = (int **) malloc( rows * sizeof(int*) );

这应该可以解决你的问题。

© www.soinside.com 2019 - 2024. All rights reserved.