Book Image

PostgreSQL Server Programming - Second Edition

Book Image

PostgreSQL Server Programming - Second Edition

Overview of this book

Table of Contents (21 chapters)
PostgreSQL Server Programming Second Edition
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

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 its own solution—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 the 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...