简体   繁体   中英

Null chars in input string after sscanf

In the following code I want to read the first 2 chars in the hex string 'a', convert them into the corresponding byte value with sscanf and put the result in 'b'. No modifications should be performed on 'a'.

#include <stdio.h>
#include <string.h>

int main()
{
    unsigned char a[]="fa23456789abcdef"; // 0-9 a-f
    unsigned char b;
    unsigned int idx = 0;

    for(idx = 0; idx < 16; idx++)
        printf("%c", a[idx]); // raw dump 'a'

    printf("\n");
    sscanf(a, "%2hhx", &b); // do sscanf
    printf("%d\n", b); // check that 'b' has been correctly updated

    for(idx = 0; idx < 16; idx++)
        printf("%c", a[idx]); // raw dump 'a'... again

    return 0;
}

Output:

fa23456789abcdef
250
   3456789abcdef

Compiler (GNU GCC in Code::Blocks):

[...]|14|warning: pointer targets in passing argument 1 of 'sscanf' differ in signedness [-Wpointer-sign]|
[...]stdio.h|348|note: expected 'const char *' but argument is of type 'unsigned char *'|
[...]|14|warning: unknown conversion type character 'h' in format [-Wformat]|
[...]|14|warning: too many arguments for format [-Wformat-extra-args]|
||=== Build finished: 0 errors, 3 warnings (0 minutes, 0 seconds) ===|

In the output the first 3 chars of 'a' are replaced with 3 null chars for no apparent reason. All the warnings are pointing to the sscanf line. Also, code::blocks for some reason doesn't like the 'h' modifier even if the 'b' value is updated correctly.

Expected result:

fa23456789abcdef
250
fa23456789abcdef

Can strtol be used alternatively in this case?

Your sscanf doesn't support hh , which means it's converting as an unsigned int and trying to stuff that into an unsigned char -sized variable, causing undefined behaviour. In your case, that means apparently overwriting part of a . Fix your warnings!

If your sscanf did support hh , you'd be fine, but you should probably still change a to be a char array instead of unsigned char .

You need to read your local sscanf documentation to figure out what you should be passing, or alternately just change b to be unsigned int and use "%2x" as your format string.

The variable a should be char , not unsigned char . With this change, I have the expected behaviour in my computer.

Here is the sscanf documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM