Why does this method throw a Segmentation fault? Why does this method throw a Segmentation fault? json json

Why does this method throw a Segmentation fault?


EDIT After looking at the source code...

for (i = parser->toknext; i < num_tokens; i++) {    jsmn_fill_token(&tokens[i], JSMN_PRIMITIVE, -1, -1);}

It initializes all of the structures but ->start and->end will equal -1, which is why memcmp is failing.

for (int i = 0; i < N_TOKENS; ++i) {    jsontok_t *key = &tokens[i];    if (key->start == -1) return NULL;    if (!memcmp("utterance", &json[key->start], (size_t) (key->end - key->start))) {        ++key;        return strndup(&json[key->start], (size_t)(key->end - key->start));    }}

Checking for a -1 value in ->start or ->end should be sufficient.


Your tokens[] array is uninitialized before you pass it to parseJson(), so once you iterate beyond the last token (the seventh one in your second example) you're trying to run memcmp() on uninitialized nonsense address values. That's causing your seg fault. Initialize tokens[] to something and then check for that initialization value in the start/end fields during your for() loop.

For example, I'd probably initialize tokens[] to zero ( via memset(&tokens, 0, sizeof(tokens)); ) and during each iteration of the loop check for length zero ( key->end - key->start ) to see if the token is actually valid before passing it to memcmp(). Bail out of the loop with a break; if the token has length zero.

(Or, if a token can have a legitimate zero-length, use some other value.)