-1
割り当てられたメモリを再利用する方法を教えてもらえますか?このコードの最終結果は、最初の配列の初期化と2番目の配列の初期化に同じ場所を使用することです。配列はconst 5です。メモリリークを修正するC++
編集:私はそれを理解しました。私はちょうど自由(nArray)を使う必要があった。行の直前に "nArray = new int [arraySize + 2];"と私はリークを修正し、同じメモリの場所を再利用することができました。
int main()
{
cout << endl << endl;
int* nArray = new int[arraySize];
cout << " --->After creating and allocating memory for nArray." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl;
for (int i = 0; i < arraySize; i++)
{
nArray[i] = i*i;
}
cout << " --->After initializing nArray." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl << endl;
for (int i = 0; i < arraySize; i++)
{
cout << " nArray[" << i << "] = " << nArray[i] << " at address <" << nArray + i << ">" << endl;
}
cout << endl << " --->Before reallocating memory for nArray." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << endl;
nArray = new int[arraySize + 2];
cout << dec << " --->After reallocating memory for nArray." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl;
for (int i = 0; i < arraySize + 2; i++)
{
nArray[i] = i*i;
}
cout << endl << " --->After reinitializing nArray." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl << endl;
for (int i = 0; i < arraySize + 2; i++)
{
cout << " nArray[" << i << "] = " << nArray[i] << " at address <" << nArray + i << ">" << endl;
}
cout << endl << " --->Getting ready to close down the program." << endl;
cout << " nArray address is <" << nArray << "> and contains the value " << hex << *nArray << dec << endl;
// Wait for user input to close program when debugging.
cin.get();
return 0;
}
C++標準では、メモリの「再利用」について何の保証もありません。特定のメモリ・チャンクを再利用する必要がある場合は、独自の低レベル・アロケータをカスタム・コンテナ用に作成する必要があります。これは明白なXY問題です。あなたが解決しようとしている真の問題は何ですか?いいえ、同じメモリの場所を使用するのではなく、同じメモリの場所を使用することが解決策であると思われる問題があれば、それを使用します。 –
ベクトルを使用して配列を管理し、サイズ変更を使用してみてください。編集に関する – rflobao
:これは絶対に保証されません。なぜなら、そこにあったものが、次の 'new'によってスペースが使用されるわけではないからです(なぜmalloc/freeとnew/deleteを混ぜるのですか?) – vu1p3n0x