【问题标题】:SegFaults in C/MySQL through Structured Con通过结构化 Con 的 C/MySQL 中的 SegFaults
【发布时间】:2014-11-10 07:40:43
【问题描述】:

嗯,我已经在这个小项目上工作了一周左右,作为我参加 C 课程的学习经验。到目前为止,我几乎没有错误地工作过,我被指示将 *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 堆栈转储/回溯

程序收到信号SIGSEGV,分段错误。 0xf7cca37e 在 mysql_close() 来自 /usr/lib/i386-linux-gnu/libmysqlclient.so.18 (gdb) 在哪里

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) 退出

我知道有 1000 个 mysql C 问题,但是它们都与我需要的东西无关,否则我现在肯定会找到它。

【问题讨论】:

    标签: mysql c linux


    【解决方案1】:

    好像是调用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 );
    }
    

    【讨论】:

    • 非常感谢。抱歉,如果我看起来很愚蠢,我只是在学习 C 和如何使用 GDB,每个答案都让我不必问更多愚蠢的问题。如果可能的话,我会给你三倍的赞成票。
    • 别担心,我能帮上忙。但是,如果您愿意,可以接受答案以明确问题已解决
    猜你喜欢
    • 1970-01-01
    • 2012-04-09
    • 2016-09-17
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    相关资源
    最近更新 更多