尝试在c ++中清除内存时双重释放或损坏

时间:2021-10-21 19:48:22

I'm writing a function that frees an array of pointers, but when I invoke the function, am getting the runtime error 'double free or corruption (fasttop)'. The purpose of the function is to clear out the array, which gets its data from an input file, if the file is already open and the fillArray function is called again.

我正在编写一个释放指针数组的函数,但是当我调用该函数时,我得到运行时错误'double free or corruption(fasttop)'。该函数的目的是清除数组,如果文件已经打开并再次调用fillArray函数,该数组将从输入文件中获取数据。

Here is the function that is causing issues:

以下是导致问题的功能:

void freeArray(Country ** g_countryArray)
{
    for (int i = 0; i < g_arrsz; ++i)
    {
        delete [] g_countryArray;
    }
}

If it's called anywhere in the program, as far as I can tell, it causes the program to crash. I've run the debugger but am not experienced enough with it to understand the output very much. I can post information from that if it would help.

如果它在程序中的任何地方被调用,据我所知,它会导致程序崩溃。我已经运行了调试器但是我没有足够的经验来理解输出。如果有帮助,我可以发布信息。

2 个解决方案

#1


0  

You left out the [i] in your loop body. You need to drop the [] if the individual pointers are to single Country objects.

你在循环体中遗漏了[i]。如果单个指针指向单个Country对象,则需要删除[]。

You might also want to delete[] the overall array; that depends on the rest of your code.

您可能还想删除[]整个数组;这取决于你的其余代码。

#2


0  

Change delete [] g_countryArray; to delete g_countryArray[i];.

更改delete [] g_countryArray;删除g_countryArray [i] ;.

delete [] arr deletes the whole array at once.

delete [] arr一次删除整个数组。

#1


0  

You left out the [i] in your loop body. You need to drop the [] if the individual pointers are to single Country objects.

你在循环体中遗漏了[i]。如果单个指针指向单个Country对象,则需要删除[]。

You might also want to delete[] the overall array; that depends on the rest of your code.

您可能还想删除[]整个数组;这取决于你的其余代码。

#2


0  

Change delete [] g_countryArray; to delete g_countryArray[i];.

更改delete [] g_countryArray;删除g_countryArray [i] ;.

delete [] arr deletes the whole array at once.

delete [] arr一次删除整个数组。