-1

I have the following function:

unsigned* b_row_to_array(b_row r) {
    unsigned a[] = {(r >> 8) & 3,
        (r >> 6) & 3,
        (r >> 4) & 3,
        (r >> 2) & 3,
        r & 3};
    return a;
}

That I wrote the following test function for:

TEST_METHOD(BRowToArrayTest) {
    unsigned expected[] = { 0, 0, 0, 0, 0 };
    unsigned* computed = b_row_to_array(0);
    for (int i = 0; i < 1; i++) {
        Assert::AreEqual(expected[i], computed[i]);
    }
}

But the test fails, saying "Expected:<0>, Actual:<42348989>", where the value for Actual is different with every test, so it must be reading in the wrong address. Am I using pointers wrong or does it read out-of-bounds because the test function is not in the same project? How can I solve this?

Arthelais
  • 606
  • 1
  • 7
  • 17
  • 3
    What is the lifetime of `a[]`? – Drew Dormann Apr 03 '15 at 15:01
  • Ah, I take it you're hinting at that a[] is no longer at the address that the pointer points to? If so, how do I resolve this, seeing as C++ doesn't allow for returning an array directly. – Arthelais Apr 03 '15 at 15:04
  • See also http://stackoverflow.com/questions/7769998 – Drew Dormann Apr 03 '15 at 15:04
  • Why can't you use a standard container, like `std::vector`? If you have to stay with your array, maybe do it the C way and pass a pointer to `a` to your function and then fill it in the function. – Unapiedra Apr 03 '15 at 15:13

1 Answers1

0

That's because your function is return a pointer to a local variable that is destroyed immediately. It's not different than had you written:

T* b_row_to_array(b_row r) {
    T a = { ... };
    return &a;
    // <== a destroyed, so we have dangling pointer
}

If you want that to work, you will need a to last. That means either allocating it:

unsigned* b_row_to_array(b_row r) {
    unsigned* a = new unsigned[5];
    ...
    return a;
}

Or returning it by value:

std::array<unsigned, 5> b_row_to_array(b_row r);
Barry
  • 286,269
  • 29
  • 621
  • 977