Re: about the magic(?) of palloc() and variable-length user-defined data type
От | Tom Lane |
---|---|
Тема | Re: about the magic(?) of palloc() and variable-length user-defined data type |
Дата | |
Msg-id | 8846.1005783985@sss.pgh.pa.us обсуждение исходный текст |
Ответ на | about the magic(?) of palloc() and variable-length user-defined data type ("Seung Hyun Jeong" <jeongs@cs.man.ac.uk>) |
Список | pgsql-hackers |
"Seung Hyun Jeong" <jeongs@cs.man.ac.uk> writes: > In the manual, I found this example: > typedef struct { > int4 length; > char data[1]; > } text; > 1) then, my first question is about the example for coding as follows: > char buffer[40]; > .... > text *destination = (text *) palloc(VARHDRSZ + 40); > .... > I cannot understand this mechanism... it looks like magic to me. No, it's simply relying on the fact that C doesn't check array subscripts. Given the stated declaration for struct text, we can access data[0], or we can (try to) access data[1], data[2], etc etc. These latter array elements are off the end of the declared structure; but if we've allocated sufficient memory, it'll work fine. This is a very standard C programming trick to get around the language's lack of explicit variable-sized arrays. If you haven't seen it before, you may need to spend more time with an introductory C textbook before you start trying to make sense of the Postgres internals... > I tried to see the source code, and found it just call MemoryContextAlloc(), > but MemoryContextAlloc() just has an empty function body. Not hardly. Where are you looking? MemoryContextAlloc is in src/backend/utils/mmgr/mcxt.c, and the function pointer it invokes generally points at AllocSetAlloc in src/backend/utils/mmgr/aset.c. > But, I have no idea what I need to set to 'internallength' for > variable-length data types. You say "variable". > If I want to make a stand-alone program which call internal functions, > especially palloc(), > to which library I need to link my program? You don't. There is no library built for the backend, only the server executable. It's pretty unclear to me what a standalone program would want with these functions anyway ... they are of no value except to something that plans to run inside a server backend process. regards, tom lane
В списке pgsql-hackers по дате отправления: