条件跳转或移动取决于未初始化的值/未初始化的值是由堆分配(realloc)创建的

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

我正在尝试转置 C 中的(非方)矩阵(就地)。

****mats
是指向动态分配的 3d 数组的指针

**ll
是一个指向动态分配数组的指针,我在其中保存每个矩阵的行数

**lc
是一个指向动态分配数组的指针,我在其中保存每个矩阵的列数

253 void transpose_mat(int ****mats, int **ll, int **lc, int k) {
254  int max_dim = (*lc)[k];
255  if ((*ll)[k] >= (*lc)[k])
256    max_dim = (*ll)[k];
257
258  (*mats)[k] = realloc((*mats)[k], max_dim * sizeof(***mats));
259  for (int i = 0; i < max_dim; ++i)
260    (*mats)[k][i] = realloc((*mats)[k][i], max_dim * sizeof(****mats));
261
262  for (int i = 0; i < max_dim; ++i) {
263    for (int j = i + 1; j < max_dim; ++j) {
264      int tmp = (*mats)[k][i][j];
265      (*mats)[k][i][j] = (*mats)[k][j][i];
266      (*mats)[k][j][i] = tmp;
267    }
268  }
269
270  int tmp = (*lc)[k];
271  (*lc)[k] = (*ll)[k];
272  (*ll)[k] = tmp;
273
274  (*mats)[k] = realloc((*mats)[k], (*ll)[k] * sizeof(***mats));
275  for (int i = 0; i < (*ll)[k]; ++i) {
276    (*mats)[k][i] = realloc((*mats)[k][i], (*lc)[k] * sizeof(****mats));
277  }
278}

Valgrind 输出

1 2
1 2 

----transpose_mat
==18654== Conditional jump or move depends on uninitialised value(s)
==18654==    at 0x484DC80: realloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==18654==    by 0x10A67A: transpose_mat (my_octave.c:260)
==18654==    by 0x10B1CC: main (my_octave.c:436)
==18654==  Uninitialised value was created by a heap allocation
==18654==    at 0x484DCD3: realloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==18654==    by 0x10A60C: transpose_mat (my_octave.c:258)
==18654==    by 0x10B1CC: main (my_octave.c:436)
==18654== 
2 1
1 
2 

---- free_k_matrix
==18654== 
==18654== HEAP SUMMARY:
==18654==     in use at exit: 0 bytes in 0 blocks
==18654==   total heap usage: 14 allocs, 14 frees, 5,212 bytes allocated
==18654== 
==18654== All heap blocks were freed -- no leaks are possible
==18654== 
==18654== For lists of detected and suppressed errors, rerun with: -s
==18654== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

我在这里缺少什么?

在为垫子重新分配内存后,我尝试初始化这些值,但最终出现更多错误和分段错误。

c valgrind dynamic-memory-allocation
1个回答
0
投票

(*mats)[k][i]
realloc((*mats)[k][i], max_dim * sizeof(****mats))
中使用之前未初始化。初始化它。

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