Max Shuu
Max Shuu

Reputation: 63

Valgrind Memcheck for PostgreSQL C function

I wrote a C Language Function for PostgreSQL. It imports data from OpenStreetMap into my own database but it seems I have a memory leak somewhere. I tried to check it with valgrind:

LD_PRELOAD='/some/path/libohdm-import.so' valgrind --leak-check=full psql ohdm-dev -c "select ohdmImport('somefile.osm');"

but every time I get the following error:

valgrind: symbol lookup error: /some/path/libohdm-import.so: undefined symbol: SPI_processed

I imported the header files from postgres correctly. The function successfully finishes with smaller map data like Fiji Islands but with bigger ones I get a Out-of-Memory.

My question is: How do I get valgrind to run with this?

Upvotes: 0

Views: 895

Answers (1)

Craig Ringer
Craig Ringer

Reputation: 325051

Error aside, this simply won't work. You're running valgrind on the psql client application, but expecting it to check for memory errors on the server backend. Your code isn't loaded into psql and valgrind can't check it there. Kind of like starting a debugger on chrome when you're tracing a crash in apache....

You will need to start the PostgreSQL server under valgrind. You should use the valgrind suppressions file supplied by PostgreSQL in src/tools/valgrind.supp, e.g. --suppressions=/path/to/postgresql/sources/src/tools/valgrind.supp.

You cannot attach valgrind memcheck to an existing process, because it needs to keep track of the process state from startup. Since PostgreSQL backends fork() from the postmaster, valgrind has to keep track of everything since postmaster start. You have to trace the whole database server.

See the PostgreSQL wiki on valgrind. In particular, note the compile options that'll help give better valgrind results.

By the way, PostgreSQL uses heirachical memory contexts, which you access with palloc, pfree, MemoryContextAlloc, SetMemoryContext etc. You should only malloc memory if you're going to pass it to another library that will free it, or you are freeing memory mallocd by a library you're using. For PostgreSQL backend code use the PostgreSQL allocators so that memory is automatically cleaned up if an exception terminates the function, etc.

Upvotes: 2

Related Questions