问题描述
好像不能动摇C6387警告。
typedef struct HashBind{
char* cKeyIdentifier;
void* vValue;
} HashBind;
....
HashBind* strNewBind = malloc(sizeof(HashBind));
strNewBind -> cKeyIdentifier = (char*) malloc((strlen(pcKey) + 1) * sizeof(char));
memcpy(strNewBind -> cKeyIdentifier,pcKey,strlen(pcKey + 1));
pcKey 是 const char* 类型。我怎样才能过去
警告 C6387 'strNewBind->cKeyIdentifier' 可能是 '0':这不符合函数 'memcpy' 的规范。
当我尝试使用 strcpy 或 strcpy_s 而不是 memcpy 时,同样适用。任何想法或任何替代方案?如何跳过 strcpy/memcpy 的这种不安全使用(防止缓冲区溢出)? C4496 and C6387 for using strcpy and strcat 没有太大帮助:/
解决方法
'strNewBind->cKeyIdentifier' 可以是 '0':这不符合函数 'memcpy' 的规范。
测试 NULL
的 malloc()
返回。
size_t n = (strlen(pcKey) + 1) * sizeof(char);
strNewBind -> cKeyIdentifier = malloc(n);
// Add test
if (strNewBind->cKeyIdentifier) {
memcpy(strNewBind -> cKeyIdentifier,pcKey,n);
} else {
Handle_OutOfMemory(); // TBD code.
}