cwarningsmemcpybuffer-overflowstrcpy

C6387 for memcpy, strcpy and strcpy_s


It seems that I cannot shake the 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));

with pcKey being a const char* type. How can I get past the

Warning C6387 'strNewBind->cKeyIdentifier' could be '0': this does not adhere to the specification for the function 'memcpy'.

Same applies when I try to use strcpy or strcpy_s, instead of memcpy. Any ideas or any alternatives? How do I skip this unsafe use of of strcpy/memcpy (prevent buffer overflow)? C4496 and C6387 for using strcpy and strcat didn't help much :/


Solution

  • 'strNewBind->cKeyIdentifier' could be '0': this does not adhere to the specification for the function 'memcpy'.

    Test for a NULL return from 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.
    }