0

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!

2
  • You're passing a null pointer as the first argument to mysql_real_connect. Commented Jul 6, 2013 at 21:46
  • I think thats right. Do this instead MYSQL conn;mysql_init(&conn);mysql_real_connect(&conn, server, user, password, database, 0, NULL, 0); Commented Jul 6, 2013 at 21:50

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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.