1

It all seems to work, but if there is a MySQL field with NULL in it I get a Segmentation Fault.

Here's the code:

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;
}

I'm calling it with

char cmd[1000];
snprintf(cmd, 999, "SELECT * FROM users WHERE id = %s", valueptr);
selectDB(cmd);
Frank Vilea
  • 8,323
  • 20
  • 65
  • 86

2 Answers2

2

From the MySQL docs:

NULL values in the row are indicated by NULL pointers. 

You need something like:

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

My only guess:

When you do:

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

it expects a pointer to a string. When you give it NULL (not a pointer to a string containing NULL, but NULL), it tries to print what's at memory location 0x00 and gives a segmentation fault.

Try checking for row[i] being a valid pointer (non-NULL) before printing it.

Also if your row has any integers in it or anything besides strings you will also get a segfault.

Claudiu
  • 224,032
  • 165
  • 485
  • 680