gpt4 book ai didi

c++ - bool变量值如何等于5?

转载 作者:太空狗 更新时间:2023-10-29 20:51:29 27 4
gpt4 key购买 nike

我有一个方法接受名为 alarm 的 bool 变量。我需要通过等于 alarm 的索引访问一些数组:

int ind = alarm; // assume here can be only '0' or '1'

但有时我会得到 Access violation reading location... 因为我的变量大于 1 - 3、5 等:

这怎么可能?
...

更新:
该问题是由于内存随机化而发生的。我用它来模拟不同的输入数据。
Microsoft Visual Studio 2015 上的完整可验证示例。

标准 Win32 控制台应用程序:

#include "stdafx.h"        
#include <stdint.h>
#include <stdlib.h>

static void randomize_memory(void* pointer, size_t size)
{
uint8_t* byteArray = reinterpret_cast<uint8_t*>(pointer);

for (int i = 0; i < size; i++)
{
byteArray[i] = rand() % 0xff;
}
}

struct MyStruct
{
double a = 0;
float b = 0;
bool flag = false;
};

int main()
{
while(true)
{
MyStruct st;
randomize_memory(&st, sizeof(st));

bool tmp = st.flag;
int ind = tmp;

if (ind > 1)
__debugbreak();
}

return 0;
}

行为经过测试并发生在编译器上从 Visual Studio 2010 (v100) 到 Visual Studio 2015 (v140)
看起来我不应该使用这种方式来模拟数据,但更糟糕的是我无法确定某些 bool 变量是否可以转换为 0-1。

最佳答案

您可能在代码中某处有未定义的行为 that is calling 设置报警开关

在 C++ 中,整数值在转换为 bool 时采用值false/true,当提升回整数类型,变为 0/1。但这并不意味着 bool 实际上是作为一个位存储或传递给函数调用的。事实上,大多数 ABI 都有每个参数的最小宽度(通常是通用寄存器的宽度),任何更短的整数类型都提升到它。

为了说明问题:

#include <iostream>

void printBool(bool x) {
std::cout << x << std::endl;
}

int main() {
int i = 5;
printBool(i);
((void(*)(int))printBool)(i); // UB
}

将打印:

1
5

编译器假设 bool 参数只能包含值 0/1 因为如果你遵循规则永远不要传入任何其他值。只有打破规则才能传递另一个值。所以then :

Using a bool value in ways described by this International Standard as “undefined,” such as by examining the value of an uninitialized automatic object, might cause it to behave as if it is neither true nor false.


另一方面,您使用 reinterpret_cast 的示例是另一个问题,我认为是 MSVC 中的错误。它在 GCC 和 clang 中运行良好。

关于c++ - bool变量值如何等于5?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49921793/

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