2012-07-17 113 views
0

我在使用valgrind的以下函數中讀取的大小無效。我不完全確定爲什麼,但如果你們中的任何人都可以幫助我,那將不勝感激!從我可以告訴它運行良好,但仍然有一些錯誤,我不捕捉,甚至可能處理內存分配和釋放。請幫忙!在valgrind中無效讀取和寫入大小

//alternate constructor that allows for setting of the inital value of the string 
MyString::MyString(const char *message) 
{ 
    int counter(0); 
    while(message[counter] != '\0') 
    { 
      counter++; 
    } 
    Size = counter; 
    **String = new char [Size];** 
    for(int i=0; i < Size; i++) 
      String[i] = message[i]; 

} 


istream& operator>>(istream& input, MyString& rhs) 
{ 
    char* t; 
    int size(256); 
    t = new char[size]; 
    input.getline(t,size); 

    **rhs = MyString(t);** 
    delete [] t; 

    return input; 
} 



/*Assignment operator (=) which will copy the source string into the destination string. Note that size of the destination needs to be adjusted to be the same as the source. 
*/ 

    MyString& MyString::operator=(const MyString& rhs) 
{ 
    if(this != &rhs) 
    { 
      delete [] String; 
      **String = new char[rhs.Size+1];** 
      Size = rhs.Size; 

      for(int i = 0; i < Size; i++) 
      { 
        ** String[i] = rhs.String[i];** 
      } 
    } 

    return *this; 
} 

有什麼建議? (所有的問題行都有**)

+0

在哪條線上? – 2012-07-17 15:23:17

+0

我應該發佈該信息,我將用某種方式突出顯示特定行的問題進行編輯。抱歉! – user1363061 2012-07-17 15:29:32

回答

0

我看到的一件事是,您的副本構造函數不會爲\0分配空間,也不會複製它。分配運算符也沒有。或者,如果不存儲終止零,那麼爲什麼要查找它?

和這兩個實現不同,爲什麼不一致(Size vs counter)?

「從我能告訴它運行良好」 - 它被稱爲未定義的行爲,或在這種情況下:運氣 - 或者,如果你喜歡我,並喜歡發現錯誤:不幸。

+0

非常感謝你!我測試了拷貝構造函數,看它是否拷貝了\ 0,並且它顯示了它。複製的字符串應該是Hello World,它將有10個字符並獲得用於nul字符的11個索引。我測試了使用cout << String [11] << endl;並打印出一張空白。當我使用String [12]時,它給了我一個隨機字符,所以我猜測它確實複製了nul。有了這個,我怎麼能確定它被複制了? – user1363061 2012-07-17 15:46:41

+0

他們究竟有什麼不同之處?我以爲我是在大小等於櫃檯的地方?我認爲在編寫代碼時我可能已經領先於自己了。 – user1363061 2012-07-17 15:54:51

+0

它不會複製它,做一個適當的測試。 – 2012-07-17 16:43:16