artaxerxe
artaxerxe

Reputation: 6411

Very confusing output on my C program

This days I posted some more questions related to that problem. Only that now I got something really interesting.

Look my code:

#include <libpq-fe.h>
#include <stdlib.h>
#include <string.h>

#define LINE_SIZE 100

PGconn *connect(char *);

int main() 
{
    connect("/path/to/file.props");
    return 0;
}

PGconn *connect(char *file_path) 
{
    const char **keywords;
    const char **values;
    char *line = malloc(LINE_SIZE);
    char *prop, *val, *tmp;
    int i = 0, j = 0, k = 0;
    PGconn *conn = NULL;
    FILE *creds = fopen(file_path, "r");
    
    if (creds == NULL) {
        perror("error: cannot open credentials file");   //!!! warning
        exit(1);
    }
    
    keywords = malloc(6 * sizeof(char *));
    values = malloc(6 * sizeof(char *));
    
    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[k++] = val;
        i = 0;
    }
    keywords[j] = NULL;
    values[k] = NULL;
    printf("%s %s %s %s %s\n", keywords[0], keywords[1], keywords[2], keywords[3], keywords[4]);
    printf("%s %s %s %s %s\n", values[0], values[1], values[2], values[3], values[4]); //prints well
    conn = PQconnectdbParams(keywords, values, 0);
    if (PQstatus(conn) != CONNECTION_OK) {
        fprintf(stderr, "%s\n", PQerrorMessage(conn));
        exit(1);
    }
    
    return conn;
}

When I run it I get the following output:

hostaddr port user password dbname

127.0.0.1 5432 my_user my_password my_db

error: cannot open credentials file: Bad address

As you can see, the file content is printed, and only after its content is printed, the error above (from line with "warning" comment) is printed like that file cannot be read.

Do you have any idea about what can happen here?

Upvotes: 0

Views: 150

Answers (1)

fceller
fceller

Reputation: 2764

"connect" is a system call to connect to a socket. I assume that PQconnextdbParams might try to use "connect" and is directed to your function again. Try to rename the function to "myconnect".

Upvotes: 7

Related Questions