Clarify comment for worst-case allocation in quote_literal_cstr()
authorMichael Paquier <[email protected]>
Mon, 7 Apr 2025 01:02:12 +0000 (10:02 +0900)
committerMichael Paquier <[email protected]>
Mon, 7 Apr 2025 01:02:12 +0000 (10:02 +0900)
palloc() is invoked with a specific formula for its allocation size in
quote_literal_cstr().  This wastes some memory, but the size is large
enough to cover even the worst-case scenarios.

No explanations were given about the reasons behind these numbers.  This
commit adds more documentation about all that.

Author: Steve Chavez <[email protected]>
Discussion: https://postgr.es/m/CAGRrpzZ9bToRWS+fAnjxDJrxwZN1QcJ-y1Pn2yg=Hst6rydLtw@mail.gmail.com

src/backend/utils/adt/quote.c

index 677efb93e8d07173a64be61f501ad20f853d59be..551de59a07f3538f603917499f0769a4d352d0aa 100644 (file)
@@ -108,7 +108,12 @@ quote_literal_cstr(const char *rawstr)
 
    len = strlen(rawstr);
    /* We make a worst-case result area; wasting a little space is OK */
-   result = palloc(len * 2 + 3 + 1);
+   result = palloc(
+                   (len * 2)   /* doubling for every character if each one is
+                                * a quote */
+                   + 3         /* two outer quotes + possibly 'E' if needed */
+                   + 1         /* null terminator */
+       );
 
    newlen = quote_literal_internal(result, rawstr, len);
    result[newlen] = '\0';