malloc因两个(几乎)相同函数之一的内存损坏而失败

时间:2018-04-04 21:27:08

标签: c malloc

我有两个相同的函数用于为矩阵分配连续的内存块,一个用于rooms = Room.objects.filter(venue=OuterRef('pk'), seatedcapacity__gte=seatedcapacity) venueslist = venueslist.annotate(has_rooms_with_capacity=Exists(rooms)) venueslist = venueslist.filter(Q(has_rooms_with_capacity=True) | Q(fullbuyoutseatedcapacity__gte=seatedcapacity)) 另一个用于int。见下文:

double

double** alloc_2d_double(int rows, int cols) { double* data = (double*)malloc(rows * cols * sizeof(double)); double** array = (double**)malloc(rows * sizeof(double)); int i; for (i = 0; i < rows; i++) { array[i] = &(data[cols*i]); } return(array); } int** alloc_2d_int(int rows, int cols) { int* data = (int*)malloc(rows * cols * sizeof(int)); int** array = (int**)malloc(rows * sizeof(int)); int i; for (i = 0; i < rows; i++) { array[i] = &(data[cols * i]); } return(array); } 函数工作正常,但int函数失败,double:内存损坏。为什么当double没有时,int函数会失败?

此代码用于mpi程序,malloc()函数查看带参数25,25和60,60的调用,double函数看到带参数27,22和100,100的调用。 / p>

非常感谢任何建议!

1 个答案:

答案 0 :(得分:1)

. v----v错误的类型。
double** array = (double**)malloc(rows * sizeof(double));的大小计算错误。

它分配给double而不是double *。因此,如果double大小与指针的大小相同或更大,那么这只是一个过度分配。

使用int** array = (int**)malloc(rows * sizeof(int));,这可能会在具有32位int和64位指针的计算机上分配不足。 @Jonathan Leffler

最好分配到取消引用指针的大小而不是类型,以避免这种常见错误。使用sizeof *pointer成语更容易编码,审核和维护。

// int** array = (int**)malloc(rows * sizeof(int));
//                   v-----------v   size of the de-referenced pointer               
int** array = malloc(sizeof *array * rows);

小点:

C中不需要转换malloc()的返回值。

int * int * size_t没有int时,请考虑size_t * int * int可能会sizeof溢出。用最宽的类型开始计算。回想一下,size_t运算符返回类型为double** alloc_2d_double(int rows, int cols) { // double* data = (double*)malloc(rows * cols * sizeof(double)); double* data = malloc(sizeof *data * rows * cols);

--system-site-packages