我在free()運行這個程序時遇到堆崩潰,但是如果我使用F10(在Visual Studio 2010中)進行調試,我就成功了。二維數組的連續內存分配---釋放內存
我的驗證碼:
以下代碼是用來免費的。有人可以解釋在這種情況下二維數組的解除分配嗎?
void Deallocate2D (SINT32 **pAccess, UINT8 i_ubyNoOfRows)
{
int i;
UINT8 *elem;
if (NULL == pAccess)
{
printf ("%d>Invalid Params\n", __LINE__);
return;
}
printf ("\nDeallocate 2D Array..................\n");
/* Include the code to deallocate the 2D array */
{
free(pAccess);
}
}
在下面的代碼是用於存儲器分配:
的代碼來填充陣列和打印數組:
SINT32 Fill2D (
SINT32 **pnAccess,
SINT32 *pnData,
UINT8 i_ubyNoOfRows,
UINT8 i_ubyNoOfCols)
{
SINT16 wRIndex, wCIndex, wDataIndex = 0;
printf ("\nFill 2D Array..................\n");
/* Include the code to fill the 2D array with the 1D values */
{
for(wRIndex = 0 ; wRIndex < 3; ++wRIndex)
for(wCIndex = 0; wCIndex < 3; ++wCIndex)
pnAccess [wRIndex][wCIndex] = pnData[wDataIndex++];
}
if ((NULL == pnAccess) \
|| (NULL == pnData))
{
printf ("%d>Invalid Params\n", __LINE__);
return -1;
}
return 0;
}
SINT32 Print2D (
SINT32 **pnAccess,
UINT8 i_ubyNoOfRows,
UINT8 i_ubyNoOfCols)
{
SINT16 wRIndex, wCIndex;
if (NULL == pnAccess)
{
printf ("%d>Invalid Params\n", __LINE__);
return -1;
}
printf ("\n2D Array..................\n\n");
/* Include the code to Print the 2D array in matrix format */
{
for(wRIndex = 0 ; wRIndex < i_ubyNoOfRows; ++wRIndex)
{
if(wRIndex % 2 == 0)
printf("\n");
for(wCIndex = 0; wCIndex < i_ubyNoOfCols; ++wCIndex)
printf("%d ", pnAccess[wRIndex][wCIndex]);
}
}
return 0;
}
在下面的代碼是一種入口點:
void Test2DArray (void)
{
SINT32 **pnData = NULL;
SINT32 nData1[] = { 10, 15, 20, 15, 20, 25, 10, 25, 20 };
SINT32 nData2[] = { 70, 75, 80, 65, 90, 25, 30, 35, 80 };
printf ("\n==================================\n");
printf ("Test 2D Array..................\n");
printf ("==================================\n\n");
if (Allocate2D(&pnData, 3, 3) != -1)
{
if (Fill2D(pnData, nData1, 3, 3) != - 1)
{
if (NULL != pnData)
{
Print2D (pnData, 3, 3);
Deallocate2D (pnData, 3);
}
}
}
if (Allocate2D(&pnData, 3, 3) != -1)
{
if (Fill2D(pnData, nData2, 3, 3) != - 1)
{
if (NULL != pnData)
{
Print2D (pnData, 3, 3);
Deallocate2D (pnData, 3);
}
}
}
}
請不要投用'malloc'返回的指針,和經驗法則很簡單:每個'malloc'調用必須與'free'調用配對。 2D數組一次不能釋放,但必須分開釋放每個指針:'char ** foo; for(int i = 0; i
@EliasVanOotegem你假定他正在使用兼容的C編譯器來編譯C代碼。 – Lundin
@lundin:沒有visual-C或C++標籤。如果OP使用VC++編譯器,他應該提及 –