C++/漏洞测试

4

我在一次面试中被问到这个问题。我完全不知道如何解决它...

/* You are writing a unit test to confirm the correctness of a function which
takes 3 float values as arguments. You decide to stress test it by testing
1000000 'random' inputs.
You find that the function will fail, but very rarely, so you include code
to print out all failure cases, hoping to grab a simple repro case which you
can debug into.
Note: All code here is run in a single-threaded environment. */

//...
// Some code sets a,b,c
//...
if ( testPasses(a,b,c) )
{
    printf("Pass\n");
}
else // someFunc fails, print the values so we can reproduce
{
    printf("Fail: %f %f %f\n", a, b, c);
}

你能帮我吗?谢谢!

更新:对不起,大家我不小心删了问题!!

这是问题:

// where testPasses has the following signature and executes deterministically 

// with no side effects:

    bool testPasses(float f1, float f2, float f3);

void testRepro()
{
    float a = // fill in from value printed by above code
    float b = // fill in from value printed by above code
    float c = // fill in from value printed by above code
    bool result = testPasses(a,b,c);
};

// Surprisingly, when you type in the 3 values printed out in testRepro()
// the test does not fail!
// Modify the original code and test bed to reproduce the problem reliably. 

那段代码不起作用吗? - Jon Cram
2
我完全不知道实际问题是什么。问题是如何编写注入随机数的循环?还是能够打印数字? - Antti Huima
1
for 循环中调用代码片段 1000000 次,每次迭代生成随机数,这样做有什么问题吗? - In silico
2个回答

7

问题在于printf对浮点数使用的精度。他们想知道你是否能看到这一点...


哦,现在我明白了,该死的,这是一个非常简单的问题。我完全可以回答它 >.< 啊啊啊啊! - Chebz

5

打印表示 float 的字节,而不是打印值。然后,您可以将精确值作为十六进制值插入。

char value[4] = { 0x12, 0x34, 0x56, 0x78 };
float *a = (float*)value;

// test using *a

严谨地说,这是不允许的。使用char value[4]来避免未定义行为。 - Ben Voigt
@Ben 我更改了它因为无论如何我都不希望将其作为生产代码,但是我很好奇,为什么使用32位整数与将其指定为char [4] 不同(除了在字节顺序上提供更明显的控制)?我真诚地好奇,因为它特别让我想起了32位int与[快速反平方根](http://en.wikipedia.org/wiki/Fast_inverse_square_root)。 - pickypg
1
在这里解释:什么是严格别名规则? - Ben Voigt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接