jansson
jansson copied to clipboard
Valgrind error when using JSON_SORT_KEYS in json_dumpf
The following small c program when checked with valgrind shows an "Invalid read of size 4" when calling json_dumpf with JSON_SORT_KEYS. If JSON_SORT_KEYS is removed then the program is fine.
/*
Valgrind error when using JSON_SORT_KEYS.
Ubuntu 12.04 (64bit). Jansson 2.7.
Compile:-
gcc -o test test.c -ljansson
Runs with expected results.
Check with valgrind:-
valgrind ./test
When JSON_SORT_KEYS is specified we get:-
Invalid read of size 4
at 0x4022CB: hashlittle
by 0x403228: hashtable_get
by 0x40457A: json_object_get
by 0x401AA7: do_dump
by 0x4016AA: do_dump
by 0x402050: json_dump_callback
by 0x401F74: json_dumpf
by 0x400E50: main
Address 0x51f339c is 44 bytes inside a block of size 47 alloc'd
at 0x4C2CC4B: malloc
by 0x403781: jsonp_malloc
by 0x403141: hashtable_set
by 0x40460D: json_object_set_new_nocheck
by 0x4046AA: json_object_set_new
by 0x400E22: main
*/
#include <stdio.h>
#include <jansson.h>
int main(int argc, char *argv[])
{
/*
[{"123456": []}]
*/
json_t *a = json_array();
json_t *b = json_object();
json_t *c = json_array();
json_object_set_new(b, "123456", c);
json_array_append_new(a, b);
/* Replace the JSON_SORT_KEYS with 0 and the valgrind error goes away */
json_dumpf(a, stdout, JSON_SORT_KEYS);
printf("\n");
json_decref(a);
return 0;
}
This is expected behavior. The hash function (hashlittle) has an optimization that Valgrind doesn't like. See the comment in https://github.com/akheron/jansson/blob/4c4f692bd6814e598c9aa538a3c9979cdf05d566/src/lookup3.h#L239-L247.
IIRC, there's currently no way to disable the optimization using the configure script. With CMake, you can disable it with the JANSSON_TEST_WITH_VALGRIND flag.