简体   繁体   中英

Segmentation fault (core dumped) on simple SQL code

I get a “Segmentation fault (core dumped)” error on some simple C++ code. The error will accure when I use the variable result. What can cause this problem in this case? I know that something goes out of range, but how is it possible that result does? There are only 2 items in the database.

#include <iostream>
#include <boost/variant.hpp>
#include <mysql/mysql.h>
#include <mysql_connection.h>

using namespace std;

const char *server = "localhost";
const char *user = "XXXX";
const char *password = "XXXX";
const char *database = "XXXX";

int main()
{
    MYSQL *conn;
    MYSQL_RES *result;
    MYSQL_ROW row;

    int num_fields = 0;

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

    mysql_query(conn, "SELECT * FROM `users` WHERE `id` = '5'");
    result = mysql_store_result(conn);

    num_fields = mysql_num_fields(result);

    while ((row = mysql_fetch_row(result)))
    {
       cout << "Spam ";
    }

    mysql_free_result(result);
    mysql_close(conn);
}

The error:

Segmentation fault (core dumped)

Process returned 139 (0x8B)   execution time : 0.255 s
Press ENTER to continue.

解决方案是建立一个符号链接,以便mysql可以找到mysql.sock:

sudo ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM