C6387 用于 memcpy、strcpy 和 strcpy_s

问题描述 投票:0回答:1

看来C6387的warning我是甩不掉了

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 和 C6387 使用 strcpy 和 strcat 没有太大帮助:/

c warnings memcpy buffer-overflow strcpy
1个回答
2
投票

“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.
}
© www.soinside.com 2019 - 2024. All rights reserved.