Basic guidelines for writing C code
After having written our first function, let's look at some of the basic coding guidelines for PostgreSQL backend coding.
Memory allocation
One of the places you have to be extra careful when writing C code in general is memory management. For any non-trivial C program you have to carefully design and implement your programs so that all your allocated memory is freed when you are done with it, or else you will "leak memory" and will probably run out of memory at some point.
As this is also a common concern for PostgreSQL it has it's own solution for it—Memory Contexts. Let's take a deeper dive into them.
Use palloc() and pfree()
Most PostgreSQL memory allocations are done using PostgreSQL's memory allocation function palloc()
and not standard C malloc()
. What makes palloc()
special, is that it allocates the memory in current context and the whole memory is freed in one go when the context is destroyed. For example, the transaction context—which is the current...