Thread: BUG #2741: Double-free on error in ECPGconnect

BUG #2741: Double-free on error in ECPGconnect

From
"Peter Harris"
Date:
The following bug has been logged online:

Bug reference:      2741
Logged by:          Peter Harris
Email address:      pharris@csl.co.uk
PostgreSQL version: 8.1 and earlier
Operating system:   Linux
Description:        Double-free on error in ECPGconnect
Details:

When using more than one database connection with ECPG, you might have
obtained and freed blocks of data on one connection before trying to open
the other.
If the second connection fails, ECPGraise will be called and call
ECPGfree_auto_mem.  This can cause an invalid free() of a pointer you've
already freed.
==========================================
/*
  demonstrate "double free on connection error" bug in libecpg

  build:
    ecpg bug.pgc
    gcc -o bug bug.c -lecpg

  test:
    valgrind ./bug

  to show what happens if you do ECPGclear_auto_mem, gcc -D FIX
*/
#ifdef FIX
  extern void ECPGclear_auto_mem(void);
#endif

EXEC SQL INCLUDE sqlca;
EXEC SQL WHENEVER SQLERROR CONTINUE;

int main(int argc, char **argv)
{
  EXEC SQL BEGIN DECLARE SECTION;
  const char **anything=NULL;
  EXEC SQL END DECLARE SECTION;

  /* first connection, should be OK */
  EXEC SQL CONNECT TO template1 AS ok_cnx;

  /* get some stuff, doesn't matter what */
  EXEC SQL AT ok_cnx SELECT datname INTO :anything FROM pg_database;

  /* free it */
  free(anything);

#ifdef FIX
  ECPGclear_auto_mem();
#endif

  /* second connection to nonexistent database */
  EXEC SQL CONNECT TO no_such_database AS crash_cnx;

  return 0;
}
==============================================
ECPGconnect should call ECPGclear_auto_mem, just as
ECPGdo does.  Patch will be posted soon...

Peter Harris