3

我尝试了以下方法来重新分配一个 2Dfloat数组,其大小从 2X2 变为 3X3。代码会抛出一段segfault时间试图realloc记忆weights[2].

num_vertices = 2;
float **weights = malloc(num_vertices*sizeof(float *));      // weight array matrix
for(i = 0; i < num_vertices; i++){
    weights[i] = malloc(num_vertices*sizeof(float));
}

num_vertices = 3;
weights = realloc(weights, num_vertices*sizeof(float *));      // weight array matrix
for(i = 0; i < num_vertices; i++){       
    weights[i] = realloc(weights[i], num_vertices*sizeof(float));
}

当然,我可以一次又一次地free使用 2D 数组malloc,但我一直在寻找更优雅的解决方案。有任何想法吗?

4

3 回答 3

5

The problem is that weights[2] contains garbage after you realloc weights.

You probably want to do something like this:

new_vertices = 3;
weights = realloc(weights, new_vertices*sizeof(float *));
for(i = 0; i < new_vertices; i++)
{
    if (i >= num_vertices)
        weights[i] = NULL;
    weights[i] = realloc(weights[i], new_vertices*sizeof(float));
}
num_vertices = new_vertices;

Note that you have a potential memory leak if realloc ever fails. Since you have no error checking yet though this probably doesn't matter for now.

于 2012-09-11T06:42:43.037 回答
3

The realloc of weights[2] is trying to realloc unallocated memory, since weights[2] was never assigned any pointer.

Usually, if you want a 2D array, just use wegihts[width*y + x] to index into the array, instead of making an array of pointers.

于 2012-09-11T06:43:08.330 回答
2

您不能循环到的顶点计数,因为外部数组的那部分尚未分配并且包含未初始化的数据。而是循环到新的num_vertices - 1并重新分配,然后创建一个全新的weights[num_verticees - 1].

于 2012-09-11T06:43:28.727 回答