尝试从C连接到postgres的问题
我正在尝试从C创建一个带有libpq的数据库连接。如果我使用PQconnectdb创建该连接,一切正常,但是如果我使用PQconnectdbParams函数创建该连接,使用相同的参数,只使用不同的存储方式(请参阅),我会得到一个分段错误,没有任何其他消息。有人能帮我解决这个问题吗 你可以看到我的代码如下:尝试从C连接到postgres的问题,c,postgresql,libpq,C,Postgresql,Libpq,我正在尝试从C创建一个带有libpq的数据库连接。如果我使用PQconnectdb创建该连接,一切正常,但是如果我使用PQconnectdbParams函数创建该连接,使用相同的参数,只使用不同的存储方式(请参阅),我会得到一个分段错误,没有任何其他消息。有人能帮我解决这个问题吗 你可以看到我的代码如下: int main(int argc, char *argv[]) { char **keywords; char **values; char
int main(int argc, char *argv[]) {
char **keywords;
char **values;
char *line = malloc(50);
char *prop, *tmp, *val;
int i = 0, j = 0;
FILE *creds = fopen("/path/to/file.props", "r");
if (creds == NULL) {
LOG("%s", "error: cannot open credentials file.\n");
exit(1);
}
keywords = malloc(5 * sizeof(*keywords));
values = malloc(5 * sizeof(*values));
while (fgets(line, LINE_SIZE, creds) != NULL) {
if (line[strlen(line) - 1] == '\n')
line[strlen(line) - 1] = '\0';
prop = line;
while(*(prop++) != '=') {
i++;
}
tmp = prop;
prop = malloc(i + 1);
strncpy(prop, line, i);
prop[i] = '\0';
keywords[j] = prop;
val = malloc(strlen(line) - strlen(prop) + 1);
strcpy(val, tmp);
values[j++] = val;
i = 0;
}
printf("%s %s %s %s %s\n", keywords[0], keywords[1], keywords[2], keywords[3], keywords[4]); //that lines prints ok
printf("%s %s %s %s %s\n", values[0], values[1], values[2], values[3], values[4]); //
PGconn *conn = PQconnectdbParams(keywords, values, 0);
if (PQstatus(conn) != CONNECTION_OK) {
fprintf(stderr, "Connection to database failed: %s", PQerrorMessage(conn));
PQfinish(conn);
exit(1);
}
}
PQconnectdbParams
的文档说明:
此函数使用参数打开一个新的数据库连接
从两个以NULL结尾的数组中获取
但是在您的代码中,关键字
和值
数组似乎是非空终止的。
它为5个参数分配了5个指针,但应该为5个参数分配6个指针,再加上一个空指针。您是否与GDB联系过?它在代码中指向哪里?你能用strtok_r()&
strdup()
代替吗?什么操作系统?像太阳光一样清晰。只需要注意细节。谢谢你的启发。:)