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.
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
or this
After the query you have to remember to free the allocated memory somewere.