Using sprintf will change the specified variable

I have a code,

char* bin2hexchar( const unsigned char& ibin, char* pbcd ) { sprintf( pbcd, "%02X", ibin ); return pbcd; } 

The problem is that the value of the ibin variable will change to zero.

Please advice.

thanks

0
source share
1 answer

If your ibin changes to zero in the caller of this function, the most likely explanation is a buffer overflow.

I suspect this is possible because the buffer that you pass as the second argument is defined as follows:

 char buff[2]; 

and ibin is next to it on the stack.

The format string %02X requires three bytes, two for characters and one for the terminating NUL character.

Even if this is not a specific case, it almost certainly overflows the buffer. If so, send the code that calls this function, along with the definitions for the corresponding variables.

+11
source

All Articles