0

有谁知道为什么以下运行时会导致分段错误?

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


}

我遵守如下

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

输出如下,

MySQL client version : 5.5.31
Segmentation fault

请帮忙!

4

2 回答 2

2

分配的对象未存储在您的代码中。因此,您将 NULL 传递给 mysql_real_connect().

更改此行:

mysql_init(conn);

至:

conn = mysql_init(conn);

或者直接:

conn = mysql_init(NULL);
于 2013-07-06T21:52:14.780 回答
1

您正在将NULL-pointer 传递给mysql_real_connect. 根据文档mysql_init返回一个初始化的MYSQL对象(当传递一个NULL-pointer 时)。将您的代码更改为此以使用返回值:

conn = mysql_init(conn);

或者这个,mysql_init填充对象:

MYSQL conn; /* note that this isn't a pointer */
mysql_init(&conn);
...
mysql_real_connect(&conn, ...);
于 2013-07-06T21:53:23.487 回答