This is a static archive of our old Q&A Site. Please post any new questions and answers at ask.wireshark.org.

How to handle an unexpected value in a value_string?

0

Hello,

I want to know how to handle an unexpected value in a value_string array. For example my array looks like the following:

static const value_string example[] = {
    {0, "result1"},
    {1, "result2"},
    {2, "result3"},
    {0, NULL}
};

If I have a value like 4, I have a STATUS_ACCESS_VIOLATION error. For me the last element {0, NULL} should avoid this unexpected behaviour, but it seems that it doesn't. Am I totally wrong? Is there any solution to my problem?

asked 07 Jan '13, 06:25

Alrik's gravatar image

Alrik
1334
accept rate: 0%

edited 07 Jan '13, 17:36

cmaynard's gravatar image

cmaynard ♦♦
9.4k1038142

For me the last instruction {0, NULL} should avoid an unexpected behaviour Yes it should, how does the code using the value string look?

(07 Jan '13, 08:06) Anders ♦

One Answer:

1

Note, in particular, that match_strval(4, example) will return NULL, and if you attempt to dereference that value your code will almost certainly crash. If you want a non-null pointer to be returned for unexpected values, use val_to_str(), not match_strval(); the third argument to val_to_str() is a format string that's used to generate the string value for an unexpected input value, for example "Unknown result (%d)" to get "Unknown result (4)" for a value of 4.

answered 07 Jan '13, 11:34

Guy%20Harris's gravatar image

Guy Harris ♦♦
17.4k335196
accept rate: 19%

Thanks for your quick answers! I use the value_string with the val_to_str() function like this: val_to_str(my_param, my_value_string, "%s")

(08 Jan '13, 00:17) Alrik
1

val_to_str(my_param, my_value_string, "%s") is not valid. The argument for the format string is a 32-bit integral value, so %s won't work - you have to use %d or %u, and you should probably also use some additional text, such as "Unknown result".

(08 Jan '13, 00:35) Guy Harris ♦♦

I tried with both %u and %d and it is still not working :( Anyway, i'll try another way to avoid this error.

Edit: After another try, I changed the right %s in %d and then it works!!! TY!!

(08 Jan '13, 01:01) Alrik

If there's more than one % format item in the third argument to val_to_str(), that's an error - only one argument is used with that string. If you're using val_to_str() to generate a format string to be later used in another call, you have to escape all the other % characters by writing them as %%.

(08 Jan '13, 03:21) Guy Harris ♦♦