gpt4 book ai didi

c - g_strdupv 函数的段错误

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

我在这个函数上遇到段错误。

/**
* Excutes the passed query and returs the the first row as an array of
* strings. You must free this array by calling g_strfreev()
*/
static gchar** mysql_single_row(MYSQL *mysql_handle, char* query){
my_ulonglong num_rows=0;
MYSQL_RES *result = NULL;
gchar ** single_row = NULL;
GString *q = g_string_new(query);
MYSQL_ROW row={0};
int query_status = mysql_real_query(mysql_handle, q->str, q->len);

if(query_status!=0){
g_string_free(q, TRUE);
return NULL;
}
fprintf(stderr, "Storing mysql result!\n");
result = mysql_store_result(mysql_handle);

if(result==NULL){
/// it was not a query that returns statemnet (e.g. INSERT, DELETE)
g_string_free(q, TRUE);
return NULL;
}

num_rows = mysql_num_rows(result);

fprintf(stderr, "Total rows = %Ld\n", num_rows);

if(num_rows>0){
/// We only fetch the first row
row = mysql_fetch_row(result);
fprintf(stderr, "Copy single rows\n");
single_row = g_strdupv(row); // <------------- SIGSEGV happens here
fprintf(stderr, "Copy single rows done\n");
}else{
mysql_free_result(result);
g_string_free(q, TRUE);
return NULL;
}

/// clean up
g_string_free(q, TRUE);
mysql_free_result(result);
return single_row;
}

基本上我想做的是执行一些“SELECT”查询并将第一行作为字符串数组返回。根据手册 g_strdupv 应该复制返回的 char ** 并创建一个新的。这个我还。稍后我使用 g_strfreev 清理它,这是推荐的方法。

但为什么我会在这里遇到段错误。我用 valgrind 运行它。输出和对应的代码可以找到here

最佳答案

g_strdupv() 复制一个以 NULL 结尾的 C 字符串数组(每个都必须以 NUL 结尾)。 C API Data Structures 上的 MySQL 文档声明 MYSQL_ROW 是一个字节字符串数组,它不一定以 NUL 结尾“如果字段值可能包含二进制数据”。因此,一个 MYSQL_ROW 既不能保证是一个以 NULL 结尾的数组,也不能保证是一个 C 字符串数组。

可能会发生段错误,因为 g_strdupv() 一直在寻找 NULL 终止符,但直到它尝试读取非进程内存时才找到终止符。

关于c - g_strdupv 函数的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11505136/

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