Database Reference
In-Depth Information
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 alloca-
tion function palloc() and not standard C malloc() . What makes palloc() spe-
cial, 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 context when a user-defined function is called—is destroyed and memory
allocated is freed at the end of transaction. This means that most times the program-
mers do not need to worry about tracking palloc() allocated memory and freeing it.
It is also easy to create your own memory contexts if you have some memory alloc-
ation needs with different life spans. For example, the functions for returning a set of
rows (described in more detail later in this chapter) have a structure passed to them,
where one of the members is reserved for a pointer to a temporary context specifically
for keeping a function-level memory context.
Zero-fill the structures
Always make sure that new structures are zero-filled, either by using memset() after
allocating them or using palloc0() .
Search WWH ::




Custom Search