diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml index 59dcea3551..fed2036236 100644 --- a/doc/src/sgml/xfunc.sgml +++ b/doc/src/sgml/xfunc.sgml @@ -1,5 +1,5 @@ @@ -947,11 +947,18 @@ typedef struct { - Obviously, the data field shown here is not long enough to hold - all possible strings; it's impossible to declare such - a structure in C. When manipulating + Obviously, the data field declared here is not long enough to hold + all possible strings. Since it's impossible to declare a variable-size + structure in C, we rely on the knowledge that the + C compiler won't range-check array subscripts. We + just allocate the necessary amount of space and then access the array as + if it were declared the right length. (If this isn't a familiar trick to + you, you may wish to spend some time with an introductory + C programming textbook before delving deeper into + Postgres server programming.) + When manipulating variable-length types, we must be careful to allocate - the correct amount of memory and initialize the length field. + the correct amount of memory and set the length field correctly. For example, if we wanted to store 40 bytes in a text structure, we might use a code fragment like this: @@ -962,9 +969,13 @@ char buffer[40]; /* our source data */ ... text *destination = (text *) palloc(VARHDRSZ + 40); destination->length = VARHDRSZ + 40; -memmove(destination->data, buffer, 40); +memcpy(destination->data, buffer, 40); ... + + VARHDRSZ is the same as sizeof(int4), but + it's considered good style to use the macro VARHDRSZ + to refer to the size of the overhead for a variable-length type.