2015-08-03 125 views
0

下面是我的結構,我暴露給用戶使用malloc給它一些大小來填充它。 使用通過我的指針這種結構C++ /結構指針/驗證成員

typedef struct ServerConfiguration { 
    wchar_t *IPAddress; 
    USHORT PortNo; 
    wchar_t *Title; 
    int repeatCount; 
    int timeout; 
} ServerConfig; 

ServerConfig *serverconfig = (ServerConfig*)malloc(sizeof(ServerConfig)); 
dcmServerconfig->IPAddress = L"localhost"; 
dcmServerconfig->Title = L"DVTK_MW_SCP"; 
dcmServerconfig->PortNo = 8080; 

用戶DOE不分配重複計數// 指向一些垃圾地址LOC //示例repeatCount = 380090700

我有具有結構的另一種結構,

typedef struct CommonParameters { 
    //other members; 
    int repeatCount 
} commonParams; 

我要驗證SERVERCONFIG值,然後將其分配給CommonParameters如示於下

if (serverConfig->opt_repeatCount > 1) { 
    commonParams.repeatCount = serverConfig->repeatCount; 
} 

如果未由用戶分配,serverConfig->repeatCount的值爲某些垃圾(380090700)。並且在我的情況下大於1。我需要驗證這個serverConfig->repeatCount是否具有有效值,然後只通過i​​f條件
最終,我的問題是驗證一個結構變量,它是一個適當值的整數。

+0

你是否想要標記這個C++? – Bathsheba

+1

'malloc'函數不初始化它分配的內存,它的內容是* indeterminate *並且使用它未初始化導致*未定義的行爲*。您需要明確初始化結構變量或面對未定義行爲的後果。 –

回答

0

你的代碼看起來像是用基於C語言的風格編寫的(即用malloc分配一塊內存,然後手動初始化結構的字段)。如果您採用更通用的基於C++的風格,您可以使用new分配內存和構造函數來初始化字段,您會發現這些問題變得更加容易。例如,你的情況,你可以寫CommonParameters爲:

struct CommonParameters { 
    CommonParameters(int rc) : 
    repeatCount(rc) 
    {} 

    //other members; 
    int repeatCount 
}; 

這樣,它的創建,你不必擔心它的初始化狀態時CommonParameters被初始化。

注意:因爲您的問題是用純C語言編寫的,您可能會錯誤地將問題標記爲C++。如果是這樣,請更改標籤,我會更新我的答案。

+0

感謝您的回覆..!我的代碼是在C++中。基本上我需要從服務器配置結構中驗證整數成員(repeatCount)的值,並將其分配給commonParameter(repeatCount)。 –

+0

如果未指定值,重複計數點的當前值爲垃圾值/地址。並且它也大於1,所以是正數(例如3800700)。我的if說,如果(repeatCount> 1)做了一些事情,並且它的執行甚至沒有分配。我的commonparams也有一個構造函數,也有一些默認值 –

+0

'typedef struct CommonParameters {0} {0} {0} int repeatCount; \t commonParams() \t { \t repeatCount = 1; \t} } commonParams; ' –