-1

「プログラムは予期せず終了しました。」

を呼び出しているクラスがありCMem::Write()ます。そして、イテレーションを画面に表示します。140 に達することもあれば、12、3、42 になることもあり、すぐに落ちます... 非常にランダムです。
への呼び出しを削除すると CMem::Write()、プログラムは永久に実行されます。

なぜそれがプログラムの終了なのかわからない? 私が推測できるのは、何かがCMem::Write()メソッドに書き込まれていないということだけです。

CMem::CMem()//sets up the "static" stack memory and the pointers to it; also the "static" positionIndex
{
    m_nBufferLength = sizeof(char); //short int
    static char *cMessageCB = new char[m_nBufferLength];
    static double *dTimeCB = new double[m_nBufferLength];

    m_cMessageCB = cMessageCB;
    m_dTimeCB = dTimeCB;


    ////////////////////////////////////////
    static char *cMessageReadList = new char[m_nBufferLength]; //max size can be the CB
    static double *dTimeReadList = new double[m_nBufferLength]; //max size can be the CB

    m_cMessageReadList = cMessageReadList;
    m_dTimeReadList = dTimeReadList;

    static int firstInstance = 0;

    if(firstInstance == 0){
        m_posRead = 0;//only on first instance
        m_posWrite = 0;//only on first instance

        firstInstance++;//check to see if multiple threads entered at the same time and look at the count
    }
}


void CMem::Write()
{//double dTime, char cMessage
//only one thread can write at a time... so lock... (make other threads with various random delays)

    static bool bUse = false;
    bool bDone = false;


    while(bDone == false){

        if(bUse == false){
            bUse = true;


            m_cMessageCB[m_posWrite] = m_cMessageWrite;
            m_dTimeCB[m_posWrite] = m_dTimeWrite;

            m_posWrite = (unsigned char)(m_posWrite + 1);


            static char cFlag = 0;
            //if writing position == reading position then flag
            if(m_posWrite == m_posRead){
                cFlag = 1;
            }

            bDone = true;
            bUse = false;
        }else if(bUse == true){
            printf("SUSPEND ");
        }
    }
}


void CMem::Read()
{//get the whole block of memory and increment the m_posRead accordingly
    unsigned char j = 0;

    while( (m_posRead + 1) != (m_posWrite + 1) ){
        m_cMessageReadList[j] = m_cMessageCB[m_posRead];//inc m_posRead at the end
        m_dTimeReadList[j] = m_dTimeCB[m_posRead];//inc m_posRead at the end

        m_posRead = (unsigned char)(m_posRead + 1);//circulate around
        j++;// 'j' is not circulating back around
    }

    //write to file
}
4

2 に答える 2

0

これらの行は、このコードの問題の 1 つと思われます。

if(firstInstance == 0){
m_posRead = 0;//only on first instance
m_posWrite = 0;//only on first instance

最初のインスタンスでのみインデックスを初期化するのはなぜですか? 他のインスタンスではこれらのメンバーが初期化されていないため、明らかにメモリが破損する可能性があります。

編集(コメントについて):

OK、静的にすることはできますが、これは設計に重大な問題があることを示しています。でもここは論外。それらを静的にした後、別の問題が残ります.m_posWrite変数はインクリメントされるだけで、リセット/デクリメントされることはありません.範囲外に出ないようにするにはどうすればよいですか?

于 2013-08-13T17:37:58.753 に答える