domlao
domlao

Reputation: 16029

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, the value of ibin variable will change to zero value.

Please advice.

Thanks

Upvotes: 0

Views: 1889

Answers (1)

paxdiablo
paxdiablo

Reputation: 882028

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

I suspect it's probably because the buffer you're passing in as the second argument is defined thus:

char buff[2];

and ibin is adjacent to it on the stack.

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

Even if that's not the specific case, it's still almost certainly buffer overflow. If so, please post the code that calls this function, along with the definitions for the relevant variables.

Upvotes: 13

Related Questions