I want to use mysql in an C code but have problem with returning result from a function. I have defined a function like this (conn is connection properly set globaly):
int _mysql_query(const char *query, MYSQL_RES *result){
int num_rows=0;
if (pthread_mutex_lock(&mysqlmutex)==0){
if (!mysql_query(conn,query)){
result=mysql_store_result(conn);
if (result!=NULL) num_rows=mysql_num_rows(result);
}
if (pthread_mutex_unlock(&mysqlmutex)!=0){
error("Error unlocking mysql mutex");
}
}else{
error("Error locking mysql mutex!");
}
return num_rows;
}
and when I call mentione function like:
MYSQL_RES *tasks;
if (_mysql_query(query,tasks)>0){
MYSQL_ROW row;
while ((row=mysql_fetch_row(tasks))!=NULL){
printf("%s\n",row[0]);
}
}
mysql_free_result(tasks);
I get segmentation fault on row=mysql_fetch_row(tasks). Why? Thanks.
You pass your pointer by value, so when your function done, you stay with previos value of pointer (uninitialized).
Solution: pass pointer to pointer i.e. &tasks
MYSQL_RES *tasks = NULL;
if (_mysql_query(query,&tasks)>0 && task!=NULL)
.........
int _mysql_query(const char *query, MYSQL_RES **result)
{
......
*result=mysql_store_result(conn);
......
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With