2015-08-03 134 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; ' –