输出 MySQL 查询结果时出现分段错误

Getting segmentation fault while outputting the result of the MySQL query

我有一个简单的程序可以打印今天的日期名称。它工作正常,但我创建了 get_query_result 函数,之后,它给了我一个分段错误。

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

#define QUERY_SIZE 1000

void finish_with_error(MYSQL* con)
{
    fprintf(stderr, "%s\n", mysql_error(con));
    mysql_close(con);
    exit(1);    
}

void get_query_result(MYSQL *con, MYSQL_RES *result, char *query)
{
    if(mysql_query(con, query))
    {
        finish_with_error(con);
    }

    result = mysql_store_result(con);

    if(result == NULL)
    {
        finish_with_error(con);
    }
}

int main()
{
    MYSQL *con = mysql_init(NULL);
    MYSQL_RES *result;
    MYSQL_ROW row;  

    if(con == NULL)
    {
            fprintf(stderr, "mysql_init() failed\n");
            exit(1);
    }

    if(mysql_real_connect(con, "127.0.0.1", "root", "mysqlpassword", "database", 0, NULL, 0) == NULL)
    {
        finish_with_error(con);
    }

    get_query_result(con, result, "SELECT DAYNAME(DATE(NOW()))");
    row = mysql_fetch_row(result);
    printf("%s\n", row[0]);

    mysql_free_result(result);

    return 0;
}
main 中的

result 不受 get_query_result 的影响,因此,您最终使用未初始化的指针调用 mysql_free_result

切换到

MYSQL_RES *get_query_result(MYSQL *con, char *query)
{
    MYSQL_RES *result;

    if(mysql_query(con, query))
    {
        finish_with_error(con);
    }

    result = mysql_store_result(con);

    if(result == NULL)
    {
        finish_with_error(con);
    }
    return result;
}

并这样称呼它:

result = get_query_result(con, "SELECT DAYNAME(DATE(NOW()))");