分段故障和阵列问题

时间:2015-07-21 21:10:19

标签: c++ windows memory segmentation-fault

我一直在努力在程序中找到分段错误。当程序崩溃时,通常就是这时。

unsigned long data = octets[g];

所以我跟踪这个缓冲区是在主循环中创建的,具有固定的定义大小。但是,因为它在main中的if语句中定义,它需要用“new”分配吗?基本上,在从TCP套接字接收后,将char缓冲区复制到unsigned char缓冲区以检查某些二进制数据类型。因此,只有当数据到达时,这才被称为存在。

INT8U byteArray[BUFFERSIZE];

然后传递此缓冲区以进行消息ID和crc检查。是不是在进行“新”类型分配问题,因为它在主循环中?我认为在“收到新数据”声明结束时它会超出范围。

long calc_crc24q(byte* octets, int start, int last) //start is first byte, last is MSbyte of CRC
{
  long crc = CRC24SEED;
  for(int g = start; g < last; g++) //should xor from preamble to the end of data
  {
    unsigned long data = octets[g]; //fault occurs here often
    crc =  crc ^ data << 16;
    for (int i = 0; i < 8; i++)
    {
      crc <<= 1;
      if (crc & 0x1000000)
      crc = crc ^ CRC24POLY;
}
  }
  return crc & 0x00ffffff; //returns an int value with high byte 00 then data in lower 3 bytes
}
//---------------------------------------------

这是消息ID

unsigned int id_message(INT8U* buffer, unsigned int posStart, unsigned int numberbytes, unsigned int& messageLength)
{
unsigned int messID = 0;
unsigned int posEnd;
unsigned int noBytes = 0;

if(buffer[posStart] == Preamble)
{
    unsigned int dataLength = (((0x0000 | buffer[posStart+1]) << 8) | buffer[posStart+2]);  //0x byte1  byte2
    messID = ((0x0000 | (buffer[posStart+3] << 4)) | ((buffer[posStart+4] >> 4) & 0x0F)); //byte1 shift 4 bits add upper 4 bits of byte 2
    noBytes = dataLength + 6;
    //numberbytes = noBytes;         
    posEnd = posStart + noBytes - 1;
            if(calc_crc24q( buffer, posStart, posEnd-2) != (((0x00000000 | buffer[posEnd-2]) << 16) | ((0x00000000 | buffer[posEnd-1]) << 8) | (0x00000000 | buffer[posEnd])) )
    {
        cout << "CRC error" << endl;
        return 0;
    }

    //return message type extracted from data segment
    messageLength = posStart + noBytes;
    return messID;
}
return 255; //unknown type
}

0 个答案:

没有答案