2012-03-29 8 views
0

私は現在、C++の書籍(プログラミング:StroustrupによるC++を使った原則と実践)のポインタについて学んでいます。この本では、私はポインタと配列に慣れるために以下の「ドリル」をしていました。私は私の問題に関係のないドリルの部分をコメントしました。ポインタのやり方の理解の問題

int num = 7; 
int* p1 = # 

// output p1 address and content... 

int* p2 = new int(10); 

// initialise each element, and output content... 

int* p3 = p2; 
p1 = p2; 

// output p1 and p2 address and content... 

delete[] p1; 

/* As all pointers now point to the same array created in the free store, 
    I was under the impression that I only needed to use delete for 1 of 
    the pointers to deallocate memory,as above, but the program crashes 
    if I don't do it for all 3 and execute next section of code? */ 

p1 = new int(10); 
p2 = new int(10); 

// Initialise each array to a different range of numbers using a loop, 
// output each array, change elements in p2 to be the same as p1, output... 

delete[] p1; 
delete[] p2; 

最後の部分は問題を抱えています。各配列を出力するとき、要素の値は同じです。私の推測では、数行前のコードのためにp1はまだ== p2です。私は、あなたが 'new'キーワードを使うとアドレスを返し、別の、新たに割り当てられたメモリブロックを参照するので、p1はもはや== p2ではないと考えました。私が動作させる唯一の方法は、2つの配列を直接作成し、p1とp2に&演算子を使用してそれらを参照させることでした。私が間違っていることについての説明は感謝しています。あなたはnewに割り当て、delete[]でメモリを解放するため

+0

の配列だけでなく、ONE整数を割り当て、10にそれを初期化していることに起因p1とp2を出力してから(値を同じにして再び出力する前に)、何を間違えているのか分かりません。 – crashmstr

答えて

2
int* p2 = new int(10); 

// initialise each element, and output content... 

int* p3 = p2; 
p1 = p2; 

// output p1 and p2 address and content... 

delete[] p1; 

このコードは、未定義の動作につながります。

int* p2 = new int(10); 
int* p3 = p2; 
p1 = p2; 
//all pointer point to the same memory location 

delete[] p1; 
//delete that memory 
//all three pointers are now invalid 

を経由して再びメモリを解放しようとすると:

int* p2 = new int(10); 
//allocates a single int with value 10 

さておき(すべての未定義の動作などの深刻な問題、が)、問題はこのだった
int* p2 = new int[10]; 
//allocates an uninitialized array of 10 ints 

異なっていますdelete p2またはdelete p3は、既にメモリを削除しているため、未定義の動作になり、クラッシュする可能性があります。そのため、新しいメモリを割り当てることでクラッシュが修正されます。

ボトムライン:同じメモリを複数回解放しないでください。

+0

うわー、私は馬鹿だと感じる。私はブラケットミスを逃したとは思わない。応答していただきありがとうございます。 – SlackerByNature

2

問題は、おそらくあなたが

p = new int(10) 

を言うとき、あなたが初期化方法を私たちに見せずにサイズ10