Hi, I'm having a problen with a certain function I wrote in C on Linux and I'm using the gdb to try to debug it. This is the prototype and the function:
Code:
char * Query(char string2[300]);
char * Query(char string2[300])
{
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "myuser";
char *password = "mypass"; /* set me first */
char *database = "mydb";
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
/* send SQL query */
mysql_query(conn,string2);
res = mysql_use_result(conn);
while ((row = mysql_fetch_row(res)) != NULL)
// printf("%s \n", row[0]);
// mysql_free_result(res);
mysql_close(conn);
return(row[0]);
}
So basically when I call the function like value=Query("SELECT COUNT(*) from table"); it returns the result in row[0] and passes it back to the variable value. This part works but ONLY if I comment out mysql_close(conn) or else I get a segmentation fault and I need to close the connection or I get too many connections after a while. Here's the output of the seg fault from gdb:
Program received signal SIGSEGV, Segmentation fault.
0x0000000000404b53 in Query (string2=0x4059e4 "select count(*) from messages") at linbbs.c:1155
1155 return(row[0]);
(gdb) bt
#0 0x0000000000404b53 in Query (string2=0x4059e4 "select count(*) from messages") at linbbs.c:1155
#1 0x0000000000404b85 in ReadMessage () at linbbs.c:1165
#2 0x00000000004043ff in MessageMenu () at linbbs.c:938
#3 0x000000000040233f in MainMenu () at linbbs.c:409
#4 0x0000000000402513 in main () at linbbs.c:487
(gdb)
If someone could help me understand my error and solve my bug it would be great. I'm still learning C so bare with me thanks.