Crash when using PQgetvalue - Mailing list pgsql-docs

From PG Doc comments form
Subject Crash when using PQgetvalue
Date
Msg-id 152812598158.26719.17918140296757658987@wrigleys.postgresql.org
Whole thread Raw
Responses Re: Crash when using PQgetvalue  (Craig Ringer <craig@2ndquadrant.com>)
List pgsql-docs
The following documentation comment has been logged on the website:

Page: https://www.postgresql.org/docs/9.5/static/libpq.html
Description:

Hello,

I am not sure if I am doing something wrong or there is a bug in the code
but I am getting a strange issue. When I try to run the following code I get
a crash when attempting to accessing the values using PQgetvalue. 

I was able to print off all the column names using PQfname. If I replace
PQgetvalue with PQgetlength the correct rows, fields and lengths are
printed. Checking PQgetisnull displayed the value as not null. I also did a
few checks using PQstatus and PQresultStatus to make sure the connection or
result set didn't mess up somehow in the middle of the code.

  PGconn *con;
  PGresult *pg_result;
  
  int i = 0;
  int j = 0;
  int cols = 0;
  int rows = 0;
  
  con = PQconnectdb("host=localhost user=postgres password=test
dbname=test");
  
  if(PQstatus(con) != CONNECTION_OK)
  {
    printf("Could not connect to PostgreSQL database!");
    fflush(stdout);
  }
  else
  {
    g_print("Connected.\n");
    
    pg_result = PQexec(con, "SELECT * FROM test");   
          
    if(PQresultStatus(pg_result) == PGRES_TUPLES_OK)
    {
      rows = PQntuples(pg_result);
      cols = PQnfields(pg_result);

      for(i = 0; i < rows; ++i)
      {
        for(j = 0; j < cols; ++j)
        {
          printf("Row: %d - Col: %d = %s\n", i, j, PQgetvalue(pg_result, i,
j)); //This is where the crash occurs. Also happens if not attempting to
print and simply getting the value or calling the function.
          fflush(stdout);
        }
      }
    }
    PQclear(pg_result);
    PQfinish(con);
    con = NULL;
  }

pgsql-docs by date:

Previous
From: Yousof Shaladi
Date:
Subject: Re: json_to_record Example
Next
From: Craig Ringer
Date:
Subject: Re: Crash when using PQgetvalue