Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :/


1 Answers

'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.
}
like image 105
chux - Reinstate Monica Avatar answered Oct 14 '25 22:10

chux - Reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!