Skip to content

Commit

Permalink
xjson: memleak in xjsonSetIndent()
Browse files Browse the repository at this point in the history
  • Loading branch information
attipaci committed Dec 18, 2024
1 parent 087a8aa commit 92b9435
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 12 deletions.
2 changes: 1 addition & 1 deletion include/xjson.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
#include <stdio.h>
#include <xchange.h>

#define XJSON_INDENT " " ///< Indentation for nested elements.
#define XJSON_DEFAULT_INDENT 2 ///< Number of characters to indent.

#ifndef NULLDEV
# define NULLDEV "/dev/null" ///< null device on system
Expand Down
35 changes: 24 additions & 11 deletions src/xjson.c
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ static int PrintString(const char *src, int maxLength, char *json);

static FILE *xerr; ///< File / stream, which errors are printed to. A NULL will print to stderr

static char *indent = XJSON_INDENT;
static int ilen = sizeof(XJSON_INDENT) - 1;
static char *indent;
static int ilen;

/**
* Sets the number of spaces per indentation when emitting JSON formatted output.
Expand All @@ -83,15 +83,23 @@ static int ilen = sizeof(XJSON_INDENT) - 1;
* @sa xjsonToString()
*/
void xjsonSetIndent(int nchars) {
if(nchars < 0) nchars = 0;
char *old;

indent = (char *) malloc(nchars + 1);
x_check_alloc(indent);
if(nchars < 0) nchars = 0;

memset(indent, ' ', nchars);
indent[nchars] = '\0';
old = indent;
indent = (char *) realloc(indent, nchars + 1);

ilen = nchars;
if(indent) {
if(nchars > 0) memset(indent, ' ', nchars);
indent[nchars] = '\0';
ilen = nchars;
}
else {
x_error(0, errno, "xjsonSetIndent", "alloc error (%d bytes)", (nchars + 1));
indent = old;
ilen = old ? strlen(old) : 0;
}
}

/**
Expand All @@ -103,7 +111,12 @@ void xjsonSetIndent(int nchars) {
* @sa xjsonToString()
*/
int xjsonGetIndent() {
return ilen;
return indent ? ilen : XJSON_DEFAULT_INDENT;
}

static char *GetIndent() {
if(!indent) xjsonSetIndent(XJSON_DEFAULT_INDENT);
return indent;
}

/**
Expand Down Expand Up @@ -994,7 +1007,7 @@ static int PrintObject(const char *prefix, const XStructure *s, char *str) {
fieldPrefix = malloc(strlen(prefix) + ilen + 1);
x_check_alloc(fieldPrefix);

sprintf(fieldPrefix, "%s%s", prefix, indent);
sprintf(fieldPrefix, "%s%s", prefix, GetIndent());

n += sprintf(str, "{\n");

Expand Down Expand Up @@ -1172,7 +1185,7 @@ static int PrintArray(const char *prefix, char *ptr, XType type, int ndim, const
rowPrefix = malloc(strlen(prefix) + ilen + 1);
x_check_alloc(rowPrefix);

sprintf(rowPrefix, "%s%s", prefix, indent);
sprintf(rowPrefix, "%s%s", prefix, GetIndent());

// Special case: empty array
if(N == 0) {
Expand Down

0 comments on commit 92b9435

Please sign in to comment.