尝试从点unsigned char获取数据时出现分段错误

时间:2015-10-16 07:56:36

标签: c++ pointers queue

我在C ++中有一个关于指针的问题。我有一个类CData,允许使用unsigned char pointer设置数据。我成功地在setData()函数中设置了一个随机指针数组。现在,我想在getData函数中显示数据。但是,它的错误是Segmentation fault (core dumped)。你能看一下我的代码,请给我解决方案。感谢

这是我当前的输出

Input is generated by random:
   103   198   105   115    81   255    74   236

Get input data:
Segmentation fault (core dumped)

这是我的完整代码。您可以在构建中无错误地运行它。

#include <iostream>
#include <stdio.h>
#include <vector>
#include <stdlib.h>
#include <string.h>
#include <queue>
#define random(x) (rand()%x)
typedef unsigned char  U8,  *PU8;
typedef unsigned int   U32, *PU32;
using std::vector;
using std::queue;

class CData
{
private:
  U8* m_Data;
  U32  m_Len;
public:

  CData(void): m_Data(NULL), m_Len(0)
  { 
  }
  ~CData(void)
  {    
  }
  CData(U8* data, U32 len): m_Data(NULL), m_Len(0) {SetData(data, len);};  
  void FreeData()
  {
    if (m_Data)
    {
      delete[] m_Data;
      m_Data = NULL;
    }
  }
  void SetData(const U8* data, U32 len)
  {
    FreeData();
    if (len > 0 && data)
    {
      m_Data = new U8[len];
      memcpy(m_Data, data, len);
      m_Len = len;
    }
  }

  U8 *GetData(void) const { return m_Data; }
  U32 GetLen(void) const { return m_Len; }

};

queue<CData*>  setData()
{
  printf("\nInput is generated by random:\n");
  U32 index = 0;
  int k=8;
  U32 dataLen=1;
  U8 *buf = new U8[dataLen];
  queue<CData*> res;
  for (U32 i = 0; i < k; ++i)
  {
    vector<U8> rndData;
    rndData.reserve(dataLen);
    for (U32 j = 0; j < dataLen; ++j)
    {
      rndData.push_back(random(256));
      index++;
      printf("%6d", rndData[j]);
      buf[j] = rndData[j];
    }
    CData data(buf, dataLen);
    res.push(&data);
  }
  printf("\n");
  delete [] buf;
  buf = NULL;
  return res;
}

void getData(queue<CData*> res_in)
{
  printf("\nGet input data:\n");
  vector<U8> out_data;
  U8 *buf =NULL;
  while (!res_in.empty())
  {    
    CData* data = res_in.front();    
    buf =data->GetData();
    int data_size = data->GetLen();
    for (int j = 0; j < data_size; ++j)
    {    
      out_data.push_back(buf[j]);
    }
    res_in.pop();
  }
  //Print output data
  for (int j = 0; j < out_data.size(); ++j)
  {    
    printf("%6d ",out_data[j]);
  }
  delete [] buf;
  buf = NULL;
}

int main(int argc, char **argv) {
    queue<CData*> res_in=setData();
    getData(res_in);
    return 0;
}

1 个答案:

答案 0 :(得分:3)

向队列推送指向本地对象(在堆栈上创建)的指针:

for (U32 i = 0; i < k; ++i)
{
    //...
    CData data(buf, dataLen);     // CData object created on the stack
    res.push(&data);              // A pointer to this object is pushed to the queue
}                                 // CData object is destroyed, as we goes out of scope