2

I am new to C but I'm currently working on a project and I am hitting a strange problem.

I have the following piece of code:

int insertID = 0;
asprintf(&inboundSql, "INSERT INTO DataTable VALUES (%i, %i, '%s', '%s', %i),"
        "(%i, %i, '%s', '%s', %i), (%i, %i, '%s', '%s', %i), (%i, %i, '%s', '%s', %i),"
        "(%i, %i, '%s', '%s', %i), (%i, %i, '%s', '%s', %i)",
        dataRow, D_DATE, callLogSearchData[dataRow].date, epochBuffer, insertID++,
        dataRow, D_TIME, callLogSearchData[dataRow].time, epochBuffer, insertID++,
        dataRow, D_APARTY, callLogSearchData[dataRow].aParty, epochBuffer, insertID++,
        dataRow, D_BPARTY, callLogSearchData[dataRow].bParty, epochBuffer, insertID++,
        dataRow, D_DURATION, durationBuffer, epochBuffer, insertID++,
        dataRow, D_RESULT, callLogSearchData[dataRow].cleardownCause, epochBuffer, insertID++);

When I compile the code, I get the following:

warning: operation on insertID may be undefined

Even though I get the above warning, my code is working as expected so I don't understand what the problem is. I guess it thinks there's something wrong with doing insertID++ but I can't see why that should be a problem.

Thanks for your help.

Boardy
  • 35,417
  • 104
  • 256
  • 447
  • You have a [combination of unspecified and undefined behavior](http://stackoverflow.com/a/18245704/1708801) it is unspecified b/c the order of evaluation of func parameters is unspecified and undefined b/c you have multiple modifications of the same variable within a sequence point. – Shafik Yaghmour Jul 22 '14 at 14:18

1 Answers1

2

This is because the exact order when function arguments are evaluated in C is not defined. Therefore you cannot be sure about the value of your insertID++'s. To fix this you should properly calculate the values to pass in different variables before calling asprintf()

Valentin Mercier
  • 5,256
  • 3
  • 26
  • 50