2016-04-03 42 views
0

我無法刪除這些兩個指針:當我運行程序,他沒有「刪除刪除多個字符指針

int *p = new int; 
    char * string1 = new char[20]; 
    char * string2 = new char[25]; 
    strcpy(string1, "Sheldon"); 

    string2 = string1; 
    delete p; 
    delete[] string2; //this works without the next line 
    delete[] string1; //when I add this, it fails at string2 = string1 

我使用的內存泄漏檢測與

#define _CRTDBG_MAP_ALLOC 
#include <stdlib.h> 
#include <crtdbg.h> 

[] string1「,它給了我」{66}在0x0075E300正常的塊,25個字節長。「所以「delete [] string2」正在刪除string1。這對我來說沒有任何意義,但我猜測它與任務有關。我試圖查找有關它的東西,但沒有任何工作。

+1

'字符串2 = string1' - 你的印象是,這是一個字符串,下副本?你爲什麼在C++中使用'char *'s而不是'std :: string's? – user2357112

+0

沒有人有時間。使用'std :: string'。 –

+0

您正在嘗試刪除相同的指針兩次。另一個在'string2 = string1;'之後丟失。 –

回答

4

代碼失敗,因爲您要刪除相同的指針兩次,導致未定義的行爲(請參閱here)。在聲明string2 = string1;之後指針string1string2保持相同的地址,並且您不能再在訪問前訪問存儲在string2中的地址,這也導致內存泄漏

如果你想string1複製到string2,你shold使用strncpy(string2, string1, 20)(見documentation)在這種情況下,指針本身保持不變,您所提供的釋放碼是有效的。

0

在分配string1之前,您必須刪除分配給string2的內存。

在分配後,string2string1是一樣的。請查看以下代碼以供參考:

int *p = new int; 
char * string1 = new char[20]; 
char * string2 = new char[25]; 
strcpy(string1, "Sheldon"); 
delete[] string2; //this would prevent memory leak 
string2 = string1; 
delete p; 

delete[] string1; //now you are releasing the memory held by string2 too. 
0

正如您已經確定的那樣,代碼中的問題是賦值。 string2 = string1;後,string2string1指向相同的內存位置。因此,當您撥打delete[] string2時,您可以免費獲得string1指出的內存。然後你打電話delete[] string1,你得到未定義的行爲作爲指針指向的內存已被釋放。也就是說,你有兩次相同的指針。

此外,您的代碼包含內存泄漏,因爲您沒有取消爲string2保留的初始內存。你應該做的是:

delete[] string2; // release the memory for string2 
    string2 = string1; // string1, string2 point to the same memory area 
    delete[] string1; // release the memory for string1 
0
char * string1 = new char[20]; 
char * string2 = new char[25]; 
strcpy(string1, "Sheldon"); 

string2 = string1; 
delete p; 
delete[] string2; //this works without the next line 
delete[] string1; //when I add this, it fails at string2 = string1 

三個問題:

  1. 原來的字符數組,其原來的變量字符串2 指出,將永遠不會被刪除。 (內存泄漏)
  2. 通過delete[] string2;指定的字符串1 將被刪除。 delete[] string2;後(回收意外內存)
  3. 通過delete[] string1;,使內存 已經被刪除,將再次刪除(失敗)