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);
3
  • Which line(s) are you getting a seg fault on? Commented May 3, 2011 at 18:46
  • i wouldn't say a dupe, necessarily... - it seems the OP didn't know that mysql can put NULL pointers in the row. Commented May 3, 2011 at 18:46
  • @Claudio- you are right. this might help him, but not a dup. sorry. Commented May 3, 2011 at 18:47

2 Answers 2

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" );
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that just confirmed my assumption.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.