frankr1977
frankr1977

Reputation: 13

segmentation fault when connecting to mysql database with c

Does anyone know why the following would cause a segmentation fault when run?

#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>

void main(void)
{
    printf("MySQL client version : %s\n", mysql_get_client_info());
    MYSQL *conn=NULL;
    mysql_init(conn);
    char *server = "localhost";
    char *user = "root";
    char *password = "pass";
    char *database = "weather";
    char *table ="room_temp";
    char *tst_qry="INSERT INTO `weather`.`room_temp` (`idx`, `date`, `temperature`) VALUES (NULL, CURRENT_TIMESTAMP, '10')";

        mysql_real_connect(conn, server, user, password, database, 0, NULL, 0);


}

I complied as follows

gcc -o mysql $(mysql_config --cflags) mysql.c $(mysql_config --libs)

The output was as follows,

MySQL client version : 5.5.31
Segmentation fault

Please help!

Upvotes: 0

Views: 4556

Answers (2)

Kninnug
Kninnug

Reputation: 8053

You're passing a NULL-pointer to mysql_real_connect. According to the documentation mysql_init returns an initialized MYSQL object (when passed a NULL-pointer). Change your code either to this to use the return value:

conn = mysql_init(conn);

or this, to have mysql_init fill the object:

MYSQL conn; /* note that this isn't a pointer */
mysql_init(&conn);
...
mysql_real_connect(&conn, ...);

Upvotes: 1

P.P
P.P

Reputation: 121407

The allocated new object isn't stored in your code. Hence you are passing the NULL to mysql_real_connect().

Change this line:

mysql_init(conn);

to:

conn = mysql_init(conn);

or rather directly:

conn = mysql_init(NULL);

Upvotes: 2

Related Questions