Skip to content

Commit

Permalink
Copy start_name and end_name out of the SPI memory context.
Browse files Browse the repository at this point in the history
Otherwise we're pointing at memory that has been freed.
  • Loading branch information
Vik Fearing committed Jul 4, 2019
1 parent 577807e commit 8837079
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions periods.c
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include "executor/spi.h"
#include "utils/elog.h"
#include "utils/rel.h"
#include "utils/memutils.h"
#include "utils/timestamp.h"

PG_MODULE_MAGIC;
Expand All @@ -33,6 +34,8 @@ GetPeriodColumnNames(Relation rel, char *period_name, char **start_name, char **
Datum values[2];
SPITupleTable *tuptable;
bool is_null;
Datum dat;
MemoryContext mcxt = CurrentMemoryContext; /* The context outside of SPI */

const char *sql =
"SELECT p.start_column_name, p.end_column_name "
Expand Down Expand Up @@ -64,11 +67,19 @@ GetPeriodColumnNames(Relation rel, char *period_name, char **start_name, char **
/* There is a unique constraint so there shouldn't be more than 1 row */
Assert(SPI_processed == 1);

/* Get the names from the result tuple */
/*
* Get the names from the result tuple. We copy them into the original
* context so they don't get wiped out by SPI_finish().
*/
tuptable = SPI_tuptable;
*start_name = NameStr(*(DatumGetName(SPI_getbinval(tuptable->vals[0], tuptable->tupdesc, 1, &is_null))));
*end_name = NameStr(*(DatumGetName(SPI_getbinval(tuptable->vals[0], tuptable->tupdesc, 2, &is_null))));

dat = SPI_getbinval(tuptable->vals[0], tuptable->tupdesc, 1, &is_null);
*start_name = MemoryContextStrdup(mcxt, NameStr(*(DatumGetName(dat))));

dat = SPI_getbinval(tuptable->vals[0], tuptable->tupdesc, 2, &is_null);
*end_name = MemoryContextStrdup(mcxt, NameStr(*(DatumGetName(dat))));

/* All done with SPI */
if (SPI_finish() != SPI_OK_FINISH)
elog(ERROR, "SPI_finish failed");
}
Expand Down

0 comments on commit 8837079

Please sign in to comment.