Getting segmentation fault while outputting the result of the MySQL query

I have a simple program that should print today’s day name. It was working, but I made the get_query_result function and after that, it is giving me a segmentation fault.

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

#define QUERY_SIZE 1000

void finish_with_error(MYSQL* con)
{
    fprintf(stderr, "%sn", 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() failedn");
            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("%sn", row[0]);

    mysql_free_result(result);

    return 0;
}

Answer

result in main is not affected by get_query_result, in consequence, you end up calling mysql_free_result with an uninitialized pointer.

Switch to

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;
}

and call it like:

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

Leave a Reply

Your email address will not be published. Required fields are marked *