Search code examples
mysqlcnullstrcpyconnector

Strcpy Null Value Obtained From MySQL in C


I am using Connector C to connect to my MySQL database. A modification that I have made to the database recently now allows the data in my url field to be NULL. Connector C does not appear to have any problems reading the NULL value, but when I try and pass the value to my array structure using strcpy, the program crashes. Here is a simplified version of my code:

mysql_real_connect(conn, server,user,password,database, port, NULL, 0);
mysql_query(conn, "SELECT * FROM main WHERE propType IN ('Single Family', 'Condominium')");
res = mysql_use_result(conn);

while (((row = mysql_fetch_row(res)) != NULL) && (row[0] != NULL)) {

    props[count].uniqueID = atol(row[0]);
    strcpy(props[count].address, row[1]);
    .
    .
    .
    strcpy(props[count].url, row[55]);
    count++;
}

By tracing out output of the rows, I have determined that it is this line of code that is failing, and it is ONLY failing when row[55] is (null):

strcpy(props[count].url, row[55]);

I am fairly new to C, and I assume that the problem lies in trying to use strcpy with a null string.

Any suggestions?


Solution

  • As is suggested above in the comment the problem is that row[55] has the value NULL and so strcpy() will crash. Maybe you want to try the following:

    if (row[55] != NULL)
        strcpy(props[count].url, row[55]);
    else
        props[count].url[0] = '\0';
    

    Here is another example code which use a bit to store if the database contains NULL or a empty value:

    if (row[55] != NULL)
    {
        strcpy(props[count].url, row[55]);
        props[count].urlEmpty = false;
    }
    else
    {
        props[count].url = '\0';          // Maybe you can skip this
        props[count].urlEmpty = true;
    }
    

    In this case you need to expand your structure.