Reputation: 53
I have program use c and c++ language to access data from MySQL database. The codes :
const char *query="SELECT * FROM myTable;";
printf("%s\n",query);
state=mysql_query(sock,query);
printf("%s\n",query);
from that code, query value from before and after 'state' statement is same (SELECT * FROM myTable;). but for this code:
const char *query=getQuery();
printf("%s\n",query);
state=mysql_query(sock,query);
printf("%s\n",query);
the function:
const char * getQuery(){
const char *returnValue;
char q[BUFSIZ];
sprintf_s(q,"%s","SELECT * FROM myTable;");
returnValue=q;
return returnValue;
}
from this code, query value from before and after "state" statement is not same,before (SELECT * FROM myTable;) and after (1/4>-uC^M).
Anybody know that?
thanks in advance.
Upvotes: 2
Views: 153
Reputation: 1929
Problem is you are returning a local variable. After the function getQuery() has been executed, q will be gone and the pointer u return points to invalid memory and reads gibberish. The reason it works before and not after the query is because the data hasn't been overwritten yet.
what you want is somthing like this
char *returnvalue = (char *) malloc(sizeof(char)*BUFSIZ);
char q[BUFSIZ];
sprintf_s(q,"%s","SELECT * FROM myTable;");
memcpy(returnvalue, q, BUFSIZ);
return returnvalue;
or this
char *returnvalue = (char *) malloc(sizeof(char)*BUFSIZ);
sprintf_s(returnvalue ,"%s","SELECT * FROM myTable;");
return returnvalue;
After the query you have to remember to free the allocated memory somewere.
free(query);
Upvotes: 4
Reputation: 69663
I think that's what's happening:
The local char array q leaves scope at the end of getQuery. That means that the memory occupied by it is deallocated. Unfortunately returnValue is still pointing to that very memory location.
Deallocated memory isn't overwritten immediately. It is marked as "free" instead and reallocated when that memory is needed. That's why the first call to printf still works: the memory wasn't needed yet, so the old data is still there. But the mysql_query function very likely needs some memory, and the memory which was once allocated for q is used. So what you now have in the address pointed to by query is some random data from the mysql_query function.
So how can this be fixed?
Allocate the memory for returnValue using malloc() or new, and then use strncopy to copy the content of q to returnValue. Just remember that the query string must be free()'ed or delete'd when # the calling program is finished with it.
Upvotes: 0