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

标签 mysql c linux

好吧,我已经在这个小项目上工作了一个星期左右,现在作为我参加 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 in mysql_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/

相关文章:

php - 加速计算速率的 SQL 查询

MySQL 仅更新第一行而不是所有行

c - 查找素数执行的程序需要一些时间

c - 矩阵乘法程序

我可以为 C 项目重新生成一个具有正确链接顺序和依赖项的 makefile 吗?

MySQL 给出 JOINed 表中每一行的结果

mysql - 如何将数据保存在 MySQL 中并将 @Id 从 GenerationType.AUTO 更改为 GenerationType.TABLE

c++ - 为什么指向函数的指针可以这样转换?

linux - FFMPEG/libav : how to match a linux lib version to a source code commit

linux - 无法评估 Dockerfile 路径 : lstat <path> no such file or directory 中的符号链接(symbolic link)