Skip to content

json_tokener_parse_verbose sets the error indicator to a wrong value when there is a memory allocation failure #857

@bhaible

Description

@bhaible

Describe the bug
The function json_tokener_parse_verbose is documented to "if it fails return the error in *error". One of the documented error values is json_tokener_error_memory. However, if there is a memory allocation failure after the first two memory allocations, the resulting error value is json_tokener_success, not (as I would expect) json_tokener_error_memory.

Steps To Reproduce
Compile and run this program foo.c on a GNU/Linux system:

#define _GNU_SOURCE 1
#include <stdlib.h>
#include <unistd.h>
#include <dlfcn.h>
#include <json.h>

void * (* libc_malloc) (size_t);
int counter = 0;
/* This malloc function works normally in the first two memory allocations, and returns NULL afterwards.  */
void *malloc (size_t n)
{
  if (++counter <= 2)
    return libc_malloc (n);
  else
    return NULL;
}

int main ()
{
  libc_malloc = dlsym (RTLD_NEXT, "malloc");
  write (1, "before\n", 7);
  enum json_tokener_error jerrno = -1;
  struct json_object *j = json_tokener_parse_verbose ("{ \"a\": 1 }", &jerrno);
  char message[] = "after: j == NULL, jerrno == json_tokener_success\n";
  message[9] = (j != NULL ? '!' : '=');
  message[25] = (jerrno != json_tokener_success ? '!' : '=');
  write (1, message, 49);
  return jerrno;
}
$ gcc -Wall -I /inst-json-c/20240329/include/json-c foo.c /inst-json-c/20240329/lib/libjson-c.a -lbsd 
$ ./a.out 
before
after: j == NULL, jerrno == json_tokener_success

Version and Platform

  • json-c version: from git, today, commit e93ae70
  • OS: Ubuntu 22.04
  • Custom cmake/build flags, if any: --prefix=/inst-json-c/20240329

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions