json - Using jsn_totext() and xbuf_empty() -
consider following simple program (run on gwan v4.3.14):
xbuf_t buf; xbuf_init(&buf); xbuf_cat(&buf, "{\"num\":-1}"); // simple json string jsn_t *jrec = jsn_frtext(buf.ptr, "rec"); // parse jsn_t *jnum = jsn_byname(jrec, "num",1); // element jsn_updt(jnum, 2); // change value positive 2 xbuf_empty(&buf); // reuse buffer puts(jsn_totext(&buf, jrec, 0)); // lets take
the expected output {"num":2}
turned out {"num":-2}
.
somehow, jsn_totext()
reused emptied xbuffer , overwrote location of '1' '2'. if jsn_update(jnum, 100)
, output correct.
is bug or did misunderstand functionality of xbuf_empty()
?
i asking quesiton because using xbuf_reset()
instead of xbuf_empty()
makes code work expected.
you have answered question: problem in code comes (mis)use of xbuf_empty()
function.
let's explain why:
the manual explains jsn_totext()
stores output in xbuffer , have "call xbuf_free(text) when done text".
it means destination xbuffer supposed unallocated yet jsn_totext()
allocate it.
you said using xbuf_reset()
works. si because call deprecated alias of xbuf_init()
function.
your confusion came fact xbuf_reset()
close xbuf_empty()
... , that's why renamed xbuf_init()
(a few years ago).
now, question raising interesting question why did not think either reuse or re-init allocated xbuffers passed jsn_totext()
.
we did not because did not think reuse same buffer. report shows, may happen, make modification other users avoid same trap.
this kind of relevant feedback makes products better time goes. thank input.
Comments
Post a Comment