【发布时间】:2011-05-31 05:02:48
【问题描述】:
我在使用 realloc 函数时遇到了一些问题。
我正在用这个函数分配一个动态二维数组:
Bubble ***allocBubblesMatrix(int height, int width) {
Bubble ***bubblesMatrix = (Bubble***) malloc(height * sizeof(Bubble**));
assert(bubblesMatrix != NULL);
int i;
for (i = 0; i < height; ++i) {
bubblesMatrix[i] = (Bubble**) malloc(width * sizeof(Bubble*));
assert(bubblesMatrix[i] != NULL);
}
int x, y;
for (y = 0; y < height; ++y)
for (x = 0; x < width; ++x)
bubblesMatrix[y][x] = newBubble(rand() % N_BUBBLES);
return bubblesMatrix;
}
使用下一个代码调用wich:
int matrixHeight = 1,
matrixWidth = MATRIX_X_SIZE;
Bubble ***bubblesMatrix = allocBubblesMatrix(matrixHeight, matrixWidth);
这样就成功创建了一个二维数组 1* MATRIX_X_SIZE。
然后,我想在矩阵中添加一行或多行,所以我使用realloc 和以下函数。它应该添加heightIncrement 行。问题是有时它可以工作,有时它会使程序崩溃。
void resizeBubblesMatrix(Bubble ****bubblesMatrix, int height, int width,
int heightIncrement) {
if (heightIncrement <= 0) /* temporary */
return;
*bubblesMatrix = (Bubble***) realloc(*bubblesMatrix, (height + heightIncrement) * sizeof(Bubble**));
assert(bubblesMatrix != NULL);
int x, y;
int newHeight = height + heightIncrement;
for (y = height; y < newHeight; ++y) {
(*bubblesMatrix)[y] = (Bubble**) malloc(width * sizeof(Bubble*));
assert((*bubblesMatrix)[y] != NULL);
for (x = 0; x < width; ++x)
(*bubblesMatrix)[y][x] = newBubble(rand() % N_BUBBLES);
}
}
这个函数被调用:
while(true) {
drawBubblesMatrix(x1, y1, matrixHeight, matrixWidth, &bubblesMatrix, bubbles);
resizeBubblesMatrix(&bubblesMatrix, matrixHeight, matrixWidth, 1);
++matrixHeight;
getch();
clear_screen(1);
}
我做错了什么?
释放之前分配的内存块的函数:
void freeBubblesMatrix(Bubble ****bubblesMatrix, int height, int width) {
int y, x;
for (y = 0; y < height; ++y) {
for (x = 0; x < width; ++x) {
free((*bubblesMatrix)[y][x]);
(*bubblesMatrix)[y][x] = NULL;
}
free((*bubblesMatrix)[y]);
(*bubblesMatrix)[y] = NULL;
}
free(*bubblesMatrix);
*bubblesMatrix = NULL;
}
提前致谢。
编辑
- 真傻。正如 Karl Knechtel 所指出的,我没有对
realloc的返回值做任何事情。但是现在程序在我每次运行时都会崩溃。 - 通过 Bart van Ingen Schenau 的回答,我证实了我所担心的:我忽略了之前分配的几个独立内存块。我什至最终得到了与 Bart 编写的代码相似的代码,但它继续使程序崩溃。
- 我添加了
assert来检查malloc/realloc调用的结果,但我没有任何运气。我在 Win98 中使用 djgpp,发生的事情真的很奇怪:- Windows:有时,它永远不会崩溃;其他的,添加 2 行后会崩溃。
- MS-DOS:添加 2 行后崩溃。 我将尝试将 -O3 与 gcc 一起使用以获取更多线索。什么是适用于 Windows 的有用(且快速学习/使用)的内存损坏/泄漏检测工具? Purify 是最佳解决方案吗?
- 甚至我释放数组的函数也返回页面错误。
【问题讨论】:
-
Bubble ****bubblesMatrix也许是时候考虑一些typedef了 -
我完全同意。我会这样做的。
标签: c dynamic multidimensional-array memory-management realloc