2

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

        }
}
1
  • did you check with GDB? where is it pointing in code? Can you use strtok_r() & strdup() instead? what OS is it? Commented Feb 23, 2013 at 10:59

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Clear like the sun's light. Only need to pay attention to details. Thanks for enlightening me.:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.