My piece of code:
void temp(char *source)
{
char dest[41];
for(int i = 0; i < 20; i++)
{
sprintf(&dest[i*2], "%02x", (unsigned int)source[i]);
}
}
When I run the static code analysis tool, I get the warning below:
On 19th iteration of the loop : This code could write past the end of the buffer pointed to by &dest[i * 2]. &dest[i * 2] evaluates to [dest + 38]. sprintf() writes up to 9 bytes starting at offset 38 from the beginning of the buffer pointed to by &dest[i * 2], whose capacity is 41 bytes.The number of bytes written could exceed the number of allocated bytes beyond that offset. The overrun occurs in stack memory.
My question is: since in every loop iteration, we are only copying 2 bytes (considering size of unsigned int on the machine is 2 bytes) from source to destination, where is the possibility of copying 9 bytes on the last iteration?
char
can be signed, and is so by default in x86 compilers. On my computerprints
ffffff80
.What you want to do is use format
"%02hhx"
and argument(unsigned char)c
.