2012年2月18日 星期六

搞甚麼 Expression:_BLOCK_TYPE_IS_VALID ??


(內文轉至巴哈姆特《三國好棒棒 哈拉版》,已取得原作者授權)
今天寫Code的時候發生一件不曾遇到的事情,就是在Debug模式下關閉程式會跳出Debug assertion: Expression:_BLOCK_TYPE_IS_VALID,爬文了半天經過一些測試才知道為什麼,根據網路上的說法在Debug模式,VC會在heap上做一些手腳,例如:你要10byte,他會偷偷給你多加一點變成11byte之類的,以方便在heap上留一點debug的資訊如leak的檢查。


很不幸的需求100bytes,而你卻copy 101bytes到這個記憶區塊中,在free記憶體時就會出現這個debug assertion,而我遇到的case如下:

class A  //沒有default copy construct & opertion=()
{
public:
    string sName;
    int iID;
    int iStride;
}

class B
{
public:
    ~B(void)
    {
       delete [] m_tempArray;
    }

    void f( A* pInput ) // pInput長度為9,且pInput是由外部程式以std::vector儲存,藉由
                        // std::vector::pointer pInput = InputArray[0];,再傳入
    {
          m_tempArray = new A[10];                               
          memcpy( tempArray, pInput, sizeof(A)*9 );  //<--問題出在這邊,好像是memcpy的時候
                                                     //多copy了一些byte到m_tempArray[10]
                                                     //所以當~B(void)的時候就會出現assection
    }

protected:
    A* m_tempArray ;
}
解決之道有兩個:
1. 為class A撰寫copy construct & opertion=()
2.不要使用memcpy function,改用迴圈的方式一個一個assign到m_tempArray中



沒有留言:

張貼留言

LinkWithin

Related Posts Plugin for WordPress, Blogger...