3

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

  • 2
    Probably the compiler is realizing that you are not checking the return of malloc, so if allocation fails and it returns NULL, you would be passing a NULL to memcpy – Ion Larrañaga Mar 26 '21 at 17:44
  • That simple... A quick if check statement after malloc and the warning is gone! Mill thanks for you time! –  Mar 26 '21 at 17:48

1 Answers1

2

'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.
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256