[英]Dynamic 2D Array with realloc gives segmentation fault, but works with malloc
I have a problem with my dynamic 2d array. 我的2D动态数组有问题。 With
malloc
it worked. 使用
malloc
可以正常工作。 With realloc
, it failed. 使用
realloc
,它失败了。
This dosen't work: 这行不通:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *const *argv) {
unsigned ** gmatrix = NULL;
int cap = 4;
/*
...
*/
gmatrix = realloc(gmatrix, 4 * sizeof(unsigned*));
for(unsigned i = 0; i < cap; i++) {
gmatrix[i] = realloc(gmatrix, cap* sizeof(unsigned));
}
// initialize:
for(unsigned i = 0; i < cap; i++) {
for(unsigned j = 0; j < cap; j++) {
gmatrix[i][j] = 0;
}
}
}
But this does: 但这确实是:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *const *argv) {
unsigned ** gmatrix = NULL;
int cap = 4;
/*
...
*/
gmatrix = malloc(cap * sizeof(unsigned*));
for(unsigned i = 0; i < cap; i++) {
gmatrix[i] = malloc(cap* sizeof(unsigned));
}
for(unsigned i = 0; i < cap; i++) {
for(unsigned j = 0; j < cap; j++) {
gmatrix[i][j] = 0;
}
}
}
In the first code part I get a segmentation fault error. 在第一个代码部分中,我遇到了分段错误错误。 Why?
为什么?
gmatrix[i] = realloc(gmatrix, cap* sizeof(unsigned));
should be 应该
gmatrix[i] = realloc(gmatrix[i], cap* sizeof(unsigned));
Using gmatrix
instead of gmatrix[i]
will lead to Undefined Behavior and the segmentation fault which you experience is one of the side-effects of Undefined Behavior . 使用
gmatrix
代替gmatrix[i]
将导致未定义行为 ,而您遇到的分段错误是未定义行为的副作用之一。
Edit : 编辑 :
You should initialize gmatrix[i]
to NULL
after the first malloc
as @MattMcNabb pointed out . @MattMcNabb 指出,在第一个
malloc
之后,应将gmatrix[i]
初始化为NULL
。 So use the following after the first call to realloc
: 因此,在第一次调用
realloc
之后使用以下命令:
for(unsigned i = 0; i < cap; i++) {
gmatrix[i] = NULL;
gmatrix[i] = realloc(gmatrix[i], cap* sizeof(unsigned));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.