gpt4 book ai didi

mysql - 通过 Structured Con 在 C/MySQL 中的 SegFaults

转载 作者:太空宇宙 更新时间:2023-11-04 11:04:18 25 4
gpt4 key购买 nike

好吧,我已经在这个小项目上工作了一个星期左右,现在作为我参加 C 类(class)的学习经验。到目前为止,我几乎没有出错,我被指示将 *con 设置为一个结构,因为我在最后得到了一个巨大的堆栈转储(这是由指针问题引起的)

我的程序一切正常。但是,在关闭 mysql 连接后,我遇到了段错误。

代码:

#include <my_global.h>
#include <mysql.h>
#include <string.h>
#include <stdlib.h>
struct sql {

MYSQL *con;

};

int try(char getInput[100]) {

struct sql grab;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = "iluvgeordi";
char *database = "test";

if( strcmp( getInput, "version" ) == 0 )
printf( "\n->Mysql Version: %s\n", mysql_get_client_info() );
else if( strcmp( getInput, "get" ) == 0 ) {

grab.con = mysql_init(NULL);

if( !mysql_real_connect(grab.con, server, user, password, database, 0, NULL, 0) ) {

fprintf(stderr, "%s\n", mysql_error(grab.con));
exit(1);

}

if( mysql_query(grab.con, "show tables") ) {

fprintf(stderr, "%s\n", mysql_error(grab.con));
exit(1);

}

res = mysql_use_result(grab.con);
if( res != NULL ) {

while( ( row = mysql_fetch_row(res) ) != NULL )
printf( "%s \n", row[0] );

}
mysql_free_result(res);

}

mysql_close(grab.con);

}

虽然我知道它是 mysql_close,但这里是 GDB 堆栈转储/回溯

Program received signal SIGSEGV, Segmentation fault. 0xf7cca37e inmysql_close () from /usr/lib/i386-linux-gnu/libmysqlclient.so.18 (gdb)where

0 0xf7cca37e in mysql_close () from /usr/lib/i386-linux-gnu/libmysqlclient.so.18

1 0x08048afa in try (getInput=0xffffd37c "version") at m-try.c:61

2 0x0804894b in main (argc=1, argv=0xffffd494) at main.c:37 (gdb) bt

0 0xf7cca37e in mysql_close () from /usr/lib/i386-linux-gnu/libmysqlclient.so.18

1 0x08048afa in try (getInput=0xffffd37c "version") at m-try.c:61

2 0x0804894b in main (argc=1, argv=0xffffd494) at main.c:37 (gdb) quit

我知道有 1000 个 mysql C 问题,但是没有一个与我需要的相关,否则我现在肯定会找到它。

最佳答案

看来错误是由 try( "version"); 的调用引起的:

1 0x08048afa in try (getInput=0xffffd37c "version") at m-try.c:61

事实上,如果您调用 try( "get"),您只需所有 mysql_init() 并为 grab.con 分配一个值但你总是调用 mysql_close( grab.con );

您应该将该调用放入“get”分支;

....
else if( strcmp( getInput, "get" ) == 0 ) {
...
mysql_close( grab.con );
}

关于mysql - 通过 Structured Con 在 C/MySQL 中的 SegFaults,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25870752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com