2

我正在使用 libpq 开发一个 postgreSQL 客户端应用程序。gcc 编译它没有错误。但是,当我运行程序时,此功能:

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();
    }
}

产生错误:

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

奇怪的是 for 循环执行前五次重复没有问题。然后它导致第六个分段错误。

我没有发布整个程序,因为它有 1000 多行。任何建议将不胜感激。

4

1 回答 1

3

这不会导致分段错误,但您发布的代码中有错误。

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

PQgetvalue函数返回 a char *,但您将其打印为int. GCC 和 Clang 都有警告,会抱怨类型不匹配,我建议-Wall -Wextra或至少-Wall。您可以使用打开格式不匹配警告-Wformat。(这个错误几乎肯定不会导致分段错误,但会导致输出不正确。)

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.

于 2012-04-28T00:10:18.043 回答