Reputation:
I am trying to integrate mysql with a gtk2 gui. It is a db client for a Mysql database. I put down the code to open the database, then try to read the records from the table and print them out in the terminal. It compiles but when I try to run it, I get a segmentation fault at the mysql_num_fields instruction.
I tried to run it and got a segmentation fault.
void openDatabase(){
MYSQL *con;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = "Excalibur&1"; /* set me first */
char *database = "people";
con = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(con, server, user, password,
database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(con));
exit(1);
}
if (mysql_query(con, "SELECT * FROM cars"))
{
fprintf("Success!");
}
res = mysql_store_result(con);
if (res == NULL)
{
fprintf("Success!");
}
int num_fields = mysql_num_fields(res);
while ((row = mysql_fetch_row(res)))
{
for(int i = 0; i < num_fields; i++)
{
printf("%s ", row[i] ? row[i] : "NULL");
}
printf("\n");
}
mysql_free_result(res);
mysql_close(con);
}
Upvotes: 1
Views: 103
Reputation: 72737
The segfault is due to fprintf("Success")
; the first arg must be a ptr-to-FILE, like stderr
.
Also, from the mysql_store_result() documentation:
Return Values
A pointer to a MYSQL_RES result structure with the results. NULL if the statement did not return a result set or an error occurred. To determine whether an error occurred, check whether mysql_error() returns a nonempty string, mysql_errno() returns nonzero, or mysql_field_count() returns zero.
You should rewrite the code to this:
if (res == NULL)
{
fprintf(stderr, "Failed\n");
exit(1);
}
In general it is useful to
Good compilers can catch printf format mismatches like this. Debuggers can show you a backtrace after a segfault and point to fprintf as the problematic call.
Upvotes: 0