2011-05-03 28 views
1

這一切似乎都有效,但如果有一個帶NULL的MySQL字段,我會得到一個分段錯誤。C程序:從包含NULL的字段中選擇MySQL時的分段錯誤

下面的代碼:

int 
selectDB(char * cmd) 
{ 
    printf("Cmd: %s\n", cmd); 
    MYSQL *conn; 
    MYSQL_RES *result; 
    MYSQL_ROW row; 
    int i; 

    conn = mysql_init(NULL); 

    if (conn == NULL) { 
     printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn)); 
     exit(1); 
    } 

     if (mysql_real_connect(conn, "localhost", "root", 
    "myPassword", "myDB", 0, NULL, 0) == NULL) 
    { 
     printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn)); 
     exit(1);  
    } 

    if (mysql_query(conn, cmd)) 
    { 
     printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn)); 
     exit(1); 
    } 

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

    while((row = mysql_fetch_row(result))) { 
     for (i=0 ; i < mysql_num_fields(result); i++) 
      printf("%s\n", row[i]); 
    } 

    if (!mysql_eof(result)) 
    { 
     printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn)); 
     exit(1); 
    } 

    mysql_free_result(result); 
    mysql_close(conn); 
    return 0; 
} 

我與

char cmd[1000]; 
snprintf(cmd, 999, "SELECT * FROM users WHERE id = %s", valueptr); 
selectDB(cmd); 
+0

哪條線(S),你得到一個賽格故障? – Chad 2011-05-03 18:46:11

+0

我不會說一個笨蛋,必然...... - 看來OP不知道mysql可以在行中放置NULL指針。 – Claudiu 2011-05-03 18:46:13

+0

@ Claudio-你是對的。這可能會幫助他,但不是一個人。抱歉。 – MByD 2011-05-03 18:47:55

回答

2

the MySQL docs

NULL values in the row are indicated by NULL pointers. 

你需要的東西,如:

for (i=0 ; i < mysql_num_fields(result); i++) 
     printf("%s\n", row[i] ? row[i] : "NULL"); 
+0

謝謝,這只是證實了我的假設。 – 2011-05-03 18:55:53

1

我唯一的猜測稱它:

當你這樣做:

printf("%s\n", row[i]); 

,預計一指向字符串的指針。當你給它NULL(不是指向包含NULL但是NULL的字符串的指針)時,它會嘗試打印內存位置0x00處的內容並給出分段錯誤。

嘗試在打印之前檢查row[i]是否爲有效指針(非NULL)。

此外,如果你的行有任何整數或任何除了字符串以外的任何東西,你也會得到一個段錯誤。