2013-05-05 59 views
0

我想在C中執行MySQL查詢,但是在調用mysql_num_rows()時出現分段錯誤。C mysql_num_rows()分段錯誤

下面是我使用的代碼:

char *username = "[email protected]"; 
char *password = "pass"; 

char query[1000]; 
int len; 
char *q = "SELECT * FROM Users WHERE `Email` = '%s' AND `Password` = '%s'"; 
len = snprintf(query, strlen(q) + strlen(username) + strlen(password), q, username, password); 
MYSQL_RES *result; 
if (db_query(query, result)) 
{ 
if (result != NULL) 
{ 
    int test_count = mysql_num_rows(result); 
    printf("%d\n", test_count); 
} 
} 
else 
{ 
printf("Query error\n"); 
} 

這裏是db_query()函數:

bool db_query(const char *query, MYSQL_RES *result) 
{ 
    if (mysql_query(db_connection, query)) 
    { 
    printf("mysql_query(): Error %u: %s\n", mysql_errno(db_connection), mysql_error(db_connection)); 

    return false; 
    } 

    if (!(result = mysql_store_result(db_connection))) 
    { 
    printf("mysql_store_result(): Error %u: %s\n", mysql_errno(db_connection), mysql_error(db_connection)); 

    return false; 
    } 

    return true; 
} 

我測試過的查詢和問題是不存在的連接也開始了。有任何想法嗎?

謝謝!

回答

3

您的問題是在這裏,在db_query功能:

if (!(result = mysql_store_result(db_connection))) 

分配給result在該函數的調用者沒有明顯的效果 - 你是按值傳遞一個指針,改變result的價值被叫方不會在調用方中對result做任何事情。

您需要更改函數以獲取指針指針,並調整調用位置和函數。

bool db_query(const char *query, MYSQL_RES **result) 
{ 
    ... 
    if (!(*result = mysql_store_result(db_connection))) 
    ... 
} 
+0

這樣做了,謝謝!看起來像我總是搞砸指針哈哈。乾杯! – user1667175 2013-05-05 12:31:45

2

任何在你db_query功能result變化反射回給調用者,因此它仍包含在創建時(如沒有初始化的自動變量它有任意值。

如果你想改變的價值有它反射回來,你應該雙指針傳遞給它,然後取消引用雙指針得到的實際值。

更妙將返回result值,並將其NULL /非NULL狀態用於成功代碼,而不是返回true/false

+0

是的,這是問題,謝謝! :) – user1667175 2013-05-05 12:39:21