【发布时间】:2013-08-13 17:25:51
【问题描述】:
“程序意外结束。”
我有一个班级正在调用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
}
【问题讨论】:
-
通常情况下,如果您在调试器中运行编解码器,它将在程序“意外完成”时停止出现问题。
-
nobody 是否发布minimal complete examples?
-
你说这是一个循环队列,但是你什么时候回绕呢?我只看到在对 CMem::Write() 的调用中增加了写入位置。你应该这样做:
if (m_posWrite == m_nBufferLength) m_posWrite = 0; -
您使用了很多静态变量。我建议改为将它们设为成员变量。在某些情况下,静态变量会导致问题。例如,这些值是否对所有类都通用?或者只是 CMem 的一个实例?如果是实例,那么它们不应该是静态的。
-
@Trenin,当你声明一个类型为 unsigned char 并且你的值是 255 时,当你将它增加 1 时会发生什么?它绕回 -1... 然后你转换它,因为操作是作为整数完成的,现在 -1 变成 0。
标签: c++ circular-buffer