【问题标题】:realloc: invalid old sizerealloc:无效的旧尺寸
【发布时间】:2017-02-19 18:48:24
【问题描述】:

我发现了很多关于此错误的线程,但一直无法找到适合我的解决方案。我正在尝试从 PGM 图像中读取数据并将其放入矩阵中。我的问题是内存的重新分配失败并出现错误realloc: invalid old size。下面是代码的摘录,显示了重新分配是如何完成的。

typedef struct num_matrix {
   int ** data;
   int rows;
   int cols;
} matrix;

[in loadPGMImageFromFilename]
matrix m;
m.data = (int**)malloc(0*sizeof(int));
loadPGMImageData(m);

[in void loadPGMImageData(matrix &m)]
ss >> m.rows >> m.cols; // <- sets rows and cols, seems to work
allocateMatrixMemory(m);

void allocateMatrixMemory(matrix &m) {
   int** temp = (int**) realloc(m.data, m.rows*sizeof(int)); // <- ERROR
   //more stuff
}

【问题讨论】:

  • (int**)malloc(0*sizeof(int));?这是故意的吗?
  • c??...
  • ss &gt;&gt; m.rows &gt;&gt; m.cols; 那应该是什么?
  • @FabianJonsson 没有“C 和 C++ 之间的混合”之类的东西,如果是 C++,它就是 C++。 :) 是的,这就是我的意思,在知道大小之前将data 指针设置为nullptr(它是C++,记住)。更好的是,把它扔掉并使用例如std::vector,毕竟你是在 C++ 中。
  • @unwind “更好的是,扔掉它并使用例如 std::vector 代替,毕竟你在 C++ 中。”。呵呵,这大概就是atm的方式吧。我不知何故陷入了我需要使用 malloc/realloc 的想法,因为我正在构建一个用 C 编写的示例代码。但由于我已经使用过 C++,我想不使用所有的 C++ 是没有意义的功能... :)

标签: c++ malloc runtime-error


【解决方案1】:

在我的脑海中, 在这行之后 -> m.data = (int**)malloc(0*sizeof(int)); m.data 为空。 您不能重新分配 null。

【讨论】:

  • 这是评论,不是答案。
  • 这可能是一个有效的指针:If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().
  • NULL 指针作为第一个参数的reallocmalloc 调用相同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-09
  • 2014-08-26
  • 2015-02-05
  • 2012-02-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多