2015-10-16 69 views
0

我在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; 
} 

回答

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 
+0

哪裏是我弄錯了?它在setData函數中,對嗎?但是,它看起來很喜歡setData函數。 – Jame

+0

@ user8430是的。您需要在堆上創建CData對象。 – Stas

+0

你能幫我解決嗎?我嘗試過,但不起作用。我在 – Jame

相關問題