程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> new-detecte時出錯,內存操作問題

new-detecte時出錯,內存操作問題

編輯:編程綜合問答
detecte時出錯,內存操作問題

#include
using namespace std;
class MyString{
private:
char* Buffer;
public:
MyString( const char* InititalInput )
{
if (InititalInput != NULL)
{
Buffer = new char[ strlen( InititalInput ) + 1 ];
strcpy_s( Buffer, strlen( InititalInput ) + 1, InititalInput );
}
else
Buffer = NULL;
}

~MyString()
{
    if (Buffer != NULL)
        delete []Buffer;
    Buffer = NULL;
}

MyString( const MyString& CopySource )
{
    if (CopySource.Buffer != NULL)
    {
        if (Buffer != NULL)
        {
            delete[]Buffer;
            Buffer = NULL;
        }

        Buffer = new char( strlen( CopySource.Buffer ) + 1 );
        strcpy_s( Buffer, strlen( CopySource.Buffer ) + 1, CopySource.Buffer );
    }
    else
        Buffer = NULL;
}

MyString& operator=( const MyString& CopySource )
{
    if (( this != &CopySource ) && ( CopySource.Buffer != NULL ))
    {
        if (Buffer != NULL)
        {
            delete[]Buffer;//錯誤提示是CRT detected that the application wrote to memory after end of heap buffer
            Buffer = NULL;//這種錯誤是由於內存操作不當造成的,可是String3之前的使用中內存分配沒少分配
        }                 //delete[]Buffer也還沒執行

        Buffer = new char( strlen( CopySource.Buffer ) + 1 );
        strcpy_s( Buffer, strlen( CopySource.Buffer ) + 1, CopySource.Buffer );
    }
    return *this;

}

operator const char*( )
{
    return Buffer;
}

};

int main()
{
MyString String1( " Hello " ), String2( " World " );
MyString String3( String1 );
cout << String1 << String2 << endl;
cout << String3 << endl;
String3 = String2;
cout << String3 << endl;
return 0;
}

最佳回答:


錯誤已發現new char[]括號打成了()

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved