Seg fault on completing query

From: Chris Jewell <vs0u8055(at)liv(dot)ac(dot)uk>
To: pgsql-interfaces(at)postgresql(dot)org
Subject: Seg fault on completing query
Date: 2003-03-13 15:28:20
Message-ID: 3E70A394.9080802@liv.ac.uk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-interfaces

Hi,

I'm working on a frontend to a Postgresql database. I've chosen C in
which to work, mainly because I wanted to learn the language. So, I'm
using the pqlib frontend library. The C source I have is below. I
compile it (on linux) with gcc -g -Wall -lpq -oantibug antibug.c. When
I run the executable, it prints out the query to the screen ok, but also
prints a "Segmentation Fault" on completion of the list. Does anyone
know why? How can I prevent this?

Thanks,

Chris J

Source:

/**************************************************************
* A test C program to perform a SELECT query on tblantibiotic*
* on the bugswat database. *
**************************************************************/

#include <stdio.h>
#include <libpq-fe.h>
#include <stdlib.h>

void exit_nicely(PGconn * conn) {
PQfinish(conn);
printf("Abnormal exit");
exit(1);
}

int main() {
/* Declare variables for the connection and getting results */
int num_records;
PGconn *connect;
PGresult *res;
int i;
char *name;

/* Connect to the database */
connect = PQconnectdb("host = linux.chrisdomain dbname=antibugdb
user=cjewell");
if (PQstatus(connect) == CONNECTION_BAD) {
fprintf(stderr, "Could not connect to database");
fprintf(stderr, "Error: %s\n", PQerrorMessage(connect));
exit_nicely(connect);
}

/* Perform our query */
res = PQexec(connect, "SELECT * FROM tblactivity;");
if ((!res) || (PQresultStatus(res) != PGRES_TUPLES_OK)) {
fprintf(stderr, "SELECT query failed, error: %d\n",
PQresultStatus(res));
fprintf(stderr, "Server error: %s\n", PQerrorMessage(connect));
PQclear(res);
exit_nicely(connect);
}

num_records = PQntuples(res); /* put the number of tuples into
num_records */

/* Now print out the results to the screen */
for(i=0; i < num_records; ++i) {
sprintf(name, "%s", PQgetvalue(res, i, 0));
printf("%s\n", name);
}

PQclear(res);
PQfinish(connect);

return(0);

}

Output:

[cjewell(at)chris cprogs]$ ./antibug
good
some
poor
none
unknown
Segmentation fault
[cjewell(at)chris cprogs]$

Responses

Browse pgsql-interfaces by date

  From Date Subject
Next Message Greg Stark 2003-03-13 15:29:03 Re: Roadmap for FE/BE protocol redesign
Previous Message Tom Lane 2003-03-13 15:19:27 Re: Roadmap for FE/BE protocol redesign