Question

I'm trying to create a database connection with libpq from C. If I create that connection with PQconnectdb, everything works fine, but if I create it with PQconnectdbParams function, with the same parameters only that stored in a different way (see libpq reference for this), I get a segmentation fault error, without any other message. Can anybody help me in that issue?

you can see my code bellow:


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

        }
}
Was it helpful?

Solution

The doc for PQconnectdbParams says:

This function opens a new database connection using the parameters taken from two NULL-terminated arrays.

But in your code it looks like the keywords and values arrays are not NULL-terminated. It allocates 5 pointers for 5 parameters but it should allocate 6 pointers for 5 parameters plus a NULL pointer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top