为什么这个例程通过了测试?

问题描述 投票:0回答:1

下面的例程有bug

线

C = (float*)malloc(N * sizeof(float));

应该是

C = (float*)malloc(N*N * sizeof(float));    

即,分配的内存比需要的少得多。

不过,例程过关了

为什么?

源代码

void Multiply(float* A, float* B, float* &C, int N)
{
    C = (float*)malloc(N * sizeof(float));
    // B is already transposed
    int loc_a, loc_b, loc_c;
    printf("In Multiply\n");
    for (int i =0; i< N; i++) {
        for (int j = 0; j<N;j++) {
            loc_c = i*N+j;
            loc_a = i*N;
            loc_b = j*N;
            C[loc_c] = 0.0f;
            for (int k=0;k<N;k++) {
                float temp = A[loc_a]*B[loc_b];
                C[loc_c] += temp;
                loc_a++;
                loc_b++;
            }
        }
    }
}

单元测试

TEST(matrix_hpp_test, matrix_multiply_with_tanspose)
{
    float *A = nullptr;
    float *B = nullptr;
    float *C = nullptr;
    CreateMatrix(A, 3, 1.0, 2.0, 3.0,
                                 4.0, 5.0, 6.0,
                                 7.0, 8.0, 9.0);
    CreateMatrix(B, 3, 1.0, 4.0, 7.0,
                                 2.0, 5.0, 8.0,
                                 3.0, 6.0, 9.0);
    Multiply(A, B, C, 3);
    ASSERT_EQ(C[0], 30);
    ASSERT_EQ(C[1], 36);
    ASSERT_EQ(C[2], 42);
    ASSERT_EQ(C[3], 66);
    ASSERT_EQ(C[4], 81);
    ASSERT_EQ(C[5], 96);
    ASSERT_EQ(C[6], 102);
    ASSERT_EQ(C[7], 126);
    ASSERT_EQ(C[8], 150);
}

输出

C:\git\test_run.exe --gtest_color=no
Testing started at 7:14 AM ...
Running 1 calendar_tests from 1 calendar_tests suite.[----------] Global calendar_tests environment set-up.
[----------] 1 calendar_tests from matrix_hpp_test
In Multiply
[----------] 1 calendar_tests from matrix_hpp_test (0 ms total)

[----------] Global calendar_tests environment tear-down
1 calendar_tests from 1 calendar_tests suite ran. (0 ms total)[  PASSED  ] 1 calendar_tests.
Process finished with exit code 0
c unit-testing malloc
1个回答
1
投票

未定义的行为意味着任何事情都可能发生,包括你想要的行为。但你不能指望它。它可以随着蝴蝶翅膀的拍打而变化,这意味着任何事情都可以让它表现得不同。不同的操作系统、编译器或程序早期发生的不同事情。

-fsanitize=address
valgrind
可以帮助找到这样的错误。

© www.soinside.com 2019 - 2024. All rights reserved.