Fix memory allocation for output of hstore type.
authorTeodor Sigaev <teodor@sigaev.ru>
Thu, 2 Apr 2009 17:57:59 +0000 (17:57 +0000)
committerTeodor Sigaev <teodor@sigaev.ru>
Thu, 2 Apr 2009 17:57:59 +0000 (17:57 +0000)
Per "maosen.zhang" <maosen.zhang@alibaba-inc.com> report.

contrib/hstore/hstore_io.c

index 9e6acd18727afb6d2588569e17c04b5067388787..99f1eaa129ba11b528754962fc361b555ec4d87c 100644 (file)
@@ -440,7 +440,8 @@ hstore_out(PG_FUNCTION_ARGS)
 {
    HStore     *in = PG_GETARG_HS(0);
    int         buflen,
-               i;
+               i,
+               nnulls=0;
    char       *out,
               *ptr;
    char       *base = STRPTR(in);
@@ -454,8 +455,15 @@ hstore_out(PG_FUNCTION_ARGS)
        PG_RETURN_CSTRING(out);
    }
 
-   buflen = (4 /* " */ + 2 /* => */ + 2 /* , */ ) * in->size +
-       2 /* esc */ * (VARSIZE(in) - CALCDATASIZE(in->size, 0));
+   for (i = 0; i < in->size; i++)
+       if (entries[i].valisnull)
+           nnulls++;
+
+   buflen = (4 /* " */ + 2 /* => */ ) * ( in->size - nnulls ) +
+       ( 2 /* " */ + 2 /* => */ + 4 /* NULL */ ) * nnulls  +
+       2 /* ,  */ * ( in->size - 1 ) +
+       2 /* esc */ * (VARSIZE(in) - CALCDATASIZE(in->size, 0)) + 
+       1 /* \0 */;
 
    out = ptr = palloc(buflen);
    for (i = 0; i < in->size; i++)