gpt4 book ai didi

c - 为什么会发生这种情况的想法? printf 让我的代码工作

转载 作者:行者123 更新时间:2023-12-01 01:39:26 25 4
gpt4 key购买 nike

我有下一个代码,基本上它所做的是读取按钮状态,如果它被按下,那么 BLE 包的制造商数据可以说是 B,相反,当按钮没有被按下时,数据是 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();
}

如果我注释掉 printf 行,那么谜语就来了,正如你所看到的那样,变量没有做任何事情,那么即使长时间按下按钮,制造商数据也永远不会改变。我试过延迟更改 printf,但没有用,读取此行之前和之后的状态并不重要,只要我正在执行指令即可。

并且出于功耗原因,我无法让 uart 模块工作。

预先感谢您的帮助

最佳答案

如评论中所述,您有未定义的行为。并且如前所述,它可能是我们看不到的东西,或者它可能是第一行:

printf("\r\n");

编辑:我认为重要的是要指出,正如@dbush 在评论中提到的那样,使用非常量参数时会出现危险(风险)。这些都是有问题的,因为它打开了格式字符串可以以开发人员不希望的方式更改的可能性。由于此示例使用的是文字字符串参数,因此不存在这种危险。

您正在使用 printf 来打印字符串,而没有使用格式说明符,例如 %s。这至少是有风险的。 ..

Because printf is a varargs function, it uses the format string to decide how many arguments it takes. If you provide one argument, but put in the format specifier, it will assume it has more arguments than it does, and read them off the stack. This will cause it to print out data from stack memory for those format strings. This can reveal information about the state of your program's memory to an attacker who adds format specifiers to the string--or just cause bugs. [emphasis mine]

引用文献: here , here here .

是否缺少 format specifier 是您描述的问题的根源,通常认为不使用 printf 是不好的做法。

关于c - 为什么会发生这种情况的想法? printf 让我的代码工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44204071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com