2

I'm working on a postgreSQL client application using libpq. gcc compiles it without error. When I run the program, however, this function:

void print_column(PGconn *connection) {

    PGresult *id_list;
    int row;

    // process_query() calls PQexec(), checks for errors, then returns the result
    id_list = process_query(connection, "SELECT id FROM customers WHERE state='CA'");

    for(row = 0; row < PQntuples(id_list); row++) {
        printf("%s\n", PQgetvalue(id_list, row, 0));

        // to pause the loop on each rep for debugging
        getchar();
    }
}

Produces the error:

row number 1701734765 is out of range 0..8
Segmentation fault

What's strange is that the for loop does the first five repetitions without a problem. Then it causes the segmentation fault on the sixth.

I didn't post the whole program because it's 1000+ lines. Any suggestions will be greatly appreciated.

contrapositive
  • 1,381
  • 2
  • 10
  • 11

1 Answers1

3

This won't cause the segmentation fault, but there is an error in the code you posted.

printf("%i\n", PQgetvalue(id_list, row, 0));

The PQgetvalue function returns a char *, but you're printing it as if it were an int. GCC and Clang both have warnings that will complain about the type mismatch, I suggest -Wall -Wextra or at least -Wall. You can turn on just the format mismatch warning by using -Wformat. (This error almost certainly won't cause a segmentation fault, but it will cause incorrect output.)

But PQgetvalue should not cause a segmentation fault (you haven't called PQclear, right?). It is possible there is an error somewhere else in your program that is corrupting memory. You can use a tool such as Valgrind to try and detect such errors. 1000 lines isn't so long that such a problem is intractable, you can also comment out various sections with #ifdef 0...#endif until the error stops, if you're desperate.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
  • The %i is a %s in the program. I was having trouble with the formatting and rewrote that part before I posted. I'll give your debugging suggestions a try and recheck my code. I'll keep you posted. – contrapositive Apr 28 '12 at 00:31