2013-01-13 21 views
-2

我不確定我是否可以在這裏發佈這些類型的問題,請讓我知道您的想法,如有必要我可以刪除該帖子。我的代碼內存操作中的錯誤

我正在試驗一些C風格的代碼,但我無法找到我的bugg。任何人都可以看到錯誤?

注:我知道有幾個內存泄漏(我會在稍後修復)

#include <cstdlib> 
#include <iostream> 
#include <string.h> 

using namespace std; 

size_t returnSize(const char* s) 
{ 
     string string(s); 
     return string.size(); 
}; 

size_t returnSize(const int& i) 
{ 
     return sizeof(i); 
}; 

size_t returnSize(const char& c) 
{ 
    return sizeof(char); 
}; 

template<typename T> 
string Serialize(const T& t) 
{ 
    T* pt = new T(t); 
    char CasttoChar[returnSize(t)]; 
    for (int i =0 ;i<returnSize(t);i++) 
    { 
     CasttoChar[i] = (reinterpret_cast<const char*>(pt)[i]); 
    } 

    char* pX = (char*)malloc(sizeof(char) * (returnSize(t) + 1)); 

    // I save size in byte 0 
    pX[0] = (char)returnSize(t); 

    //I save value in subsequent bytes. 
    for (int i = 1 ; i<=returnSize(t) ; i++) 
    { 
     pX[i] = CasttoChar[i];       
    } 

    string returnString(pX); 
    free(pX); 

    return returnString;  
}; 
template<typename T> 
T DeSerialize(const string& s) 
{ 
    const char * cstr = s.c_str(); 

    int sizeofData = (int)cstr[0]; 

    char* cp = (char*)malloc(sizeof(char) * sizeofData); 
    for (int i =0 ;i<sizeofData;i++) 
    { 
     cp[i] = cstr[i];       
    } 

    T* result= reinterpret_cast<T*>(cp); 

    return *result; 

} 
int main(int argc, char *argv[]) 
{ 
    int x = 10; 
    string s = Serialize(x); 
    cout << DeSerialize<int>(s); 
    /*  
    I need to see: 
    10 as output 
    now I see 4 
    */  
    system("PAUSE"); 
    return EXIT_SUCCESS; 
} 

所以基本上我序列號10,當我反序列化,我得到4

+0

要求人們在代碼中發現錯誤不是生產力。您應該使用調試器(或添加打印語句)來隔離問題,然後構造一個[最小測試用例](http://sscce.org)。 –

+0

你說你有一個錯誤,但沒有解釋錯誤是什麼。 – Steve

+0

啊,我完全同意,不幸的是,我正在一臺非常古老的PC上工作,安裝一個調試器並不適合我。 – Kam

回答

1

要複製的錯誤字節:

for (int i =0 ;i<sizeofData;i++) 
{ 
    cp[i] = cstr[i];       
} 

由於CSTR [0]是長度,它應該是:

for (int i =0 ;i<sizeofData;i++) 
{ 
    cp[i] = cstr[i+1];       
} 

[此外,你需要確保你的字符串不能超過128個大小!]

哦,進一步:傳遞一個char*std::string假設你的字符串是C風格的字符串。所以,如果你的字符串中有一個零字節,它將不起作用。可能最好有一個數據結構,它只是一個長度和一個動態分配的char數組。

我也相信你會從std::string類型複製錯誤的字節,因爲你只是將字符串的地址轉換爲char *,這就是「object std :: string」,而不是實際的字符串內容 - 你需要「c_str()」。錯誤的

0

一個來源:

string s = Serialize(x); 

應該

string s = Serialize<int>(x); 
+1

呃?爲什麼?編譯器應該能夠將其排除。 –