2017-04-11 92 views
1

我試圖運行用C++編寫的MySQL UDF。它編譯得很好並生成正確的輸出,但是在輸出後會產生很多垃圾。我想知道這個垃圾的原因以及我如何解決這個問題?我附上了我的代碼和輸出的截圖。C++中的MySQL用戶定義函數

#include <iostream> 
#include <algorithm> 
#include <string> 
#include <cstdlib> 
#include <cstdio> 
#include <cstring> 
#include "mysql-connector-c-6.1.9-linux-glibc2.5-x86_64/include/mysql.h" 
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/mysql_connection.h" 
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/cppconn/sqlstring.h" 
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/cppconn/resultset.h" 
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/cppconn/datatype.h" 
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/cppconn/resultset.h" 
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/cppconn/resultset_metadata.h" 
#include "mysql-connector-c++-1.1.8-linux-ubuntu16.04-x86-64bit/include/cppconn/exception.h" 

using namespace std; 

extern "C" { 
    char *hello_world (UDF_INIT *initid, UDF_ARGS *args,char *result, unsigned long length,char *is_null, char *error); 
    my_bool hello_world_init (UDF_INIT *initid, UDF_ARGS *args, char *message); 
    void hello_world_deinit (UDF_INIT *initid); 
    //template <typename T> T adder (UDF_INIT *initid, UDF_eARGS *args,string result, unsigned long length,string is_null, string error,T v); 
} 

char *hello_world (UDF_INIT *initid, UDF_ARGS *args, char *result, unsigned long length, char *is_null, char *error) 
{ 
    string res; 
    res = args->args[0]; 
    res.append(" hello"); 
    char *c = new char[res.size()]; 
    strcpy(c, res.c_str()); 
    return c; 
} 

my_bool hello_world_init (UDF_INIT *initid, UDF_ARGS *args, char *message) 
{ 
    return 0; 
    //cout<<"success"<<endl; 
} 

void hello_world_deinit (UDF_INIT *initid) 
{ 
    return; 
} 

enter image description here

+0

您作爲結果分配的數組太小。您需要爲終止零添加一個字符:'new char [res.size()+ 1]'。 –

+0

您爲結果分配的緩衝區將導致內存泄漏。 您需要在'xxx_init'和'xxx_deinit'函數中管理內存:預先分配一個緩衝區來存儲結果,然後釋放它。 –

回答

2

hello_world函數的簽名是錯誤的。第四個參數應該是

unsigned long *length 

該指針指向的值必須設置爲返回字符串的長度。

char *c = new char[res.size() + 1]; 
strcpy(c, res.c_str()); 
*length = res.size(); 
return c; 
+0

解決了上述編輯非常感謝@Marvin –