I'm trying to copy a uint8_t* into an char array, the uint8_t* is non terminating but I have another uint8_t with the length of the message. How do I copy the uint8_t* into a char array without getting segfauts.
uint8_t *name; //Set to something beforehand, it's part of an server STUN.
uint8 name_length; //Also set to something I just know is less than 255.
//I've tried
char nameArray[255];
memcpy(nameArray, name, name_length-1);
nameArray[name_length] = '\0';
Segfaults due to invalid read size
Because of integer promotion of the variable name_length
at the call site of memcpy()
is converted into int
. If the value is 0 (zero) the subtraction of 1 results in a value of -1. This is then converted into size_t
which gives SIZE_MAX. memcpy()
happily starts copying that amount but runs beyond the limit of the allowed address range.
Since the subtraction of 1 is wrong in the first place, remove it.