morfeus
morfeus

Reputation: 33

Function in C returning MYSQL_RES

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.

Upvotes: 3

Views: 2304

Answers (1)

Dabo
Dabo

Reputation: 2373

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);    
      ......

Upvotes: 1

Related Questions