Ideas why this might be happening? printf makes my code work

I have the following code, basically what it does is read the state of a button, and if it is pressed, the BLE package maker data lets say B, conversely, when the button is not pressed, the data is A.

while (true) {

    printf("\r\n");

    if ((int)nrf_gpio_pin_read(PIN_IN)) {

            //Setting up the advertising data with scan response data = Null
            err_code = sd_ble_gap_adv_data_set(Conectado, Conectado_length,
                    0, 0);
            APP_ERROR_CHECK(err_code);

    } else {
            //Setting up the advertising data with scan response data = Null

            err_code = sd_ble_gap_adv_data_set(Prueba,
                    Conectado_length, 0, 0);
            APP_ERROR_CHECK(err_code);
    }

    power_manage();
}

      

The puzzle arises if I comment out the printf line, which as you can see does nothing with this variable, the producer data never changes, even if the button is pressed for a long time. I tried changing printf to delay, doesn't work, reading the state before and after this line, it doesn't matter if I execute the statement.

And for power consumption reasons, I cannot work with the uart module.

Thanks in advance for your help

+3


source to share


1 answer


You have undefined behavior as pointed out in the comments. And, as mentioned, it could be something we can't see, or it could be the very first line:

printf("\r\n");

      

Edit: I think it is important to point out, as @dbush mentioned in the comments, the danger (risk) comes from using volatile arguments. This is problematic as it opens up the possibility that the format string could be changed in ways that the developer did not intend. Since this example uses a string argument, this danger does not exist.

You are using printf

to print strings without using a format specifier eg %s

. It's risky at least ...



Since printf is a varargs function, it uses a format string to decide how many arguments are required. If you provide one argument, but put in a format specifier, it will assume that it has more arguments than it does and pops them off the stack. This will cause it to print data from stack memory for those format strings. This can expose information about the state of your program memory to an attacker who adds format specifiers to a string - or simply causes errors . [my accent]

Refernces: here , here and here .

Whether the source of the problem description is the source of the problem you are describing is generally considered bad practice to use printf

without one.

+2


source







All Articles