Unit testing a function that returns a pointer (C++) -
Unit testing a function that returns a pointer (C++) -
this question has reply here:
pointer local variable 8 answersi have next 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}; homecoming a; }
that wrote next test function for:
test_method(browtoarraytest) { unsigned expected[] = { 0, 0, 0, 0, 0 }; unsigned* computed = b_row_to_array(0); (int = 0; < 1; i++) { assert::areequal(expected[i], computed[i]); } }
but test fails, saying "expected:<0>, actual:<42348989>", value actual different every test, must reading in wrong address. using pointers wrong or read out-of-bounds because test function not in same project? how can solve this?
that's because function homecoming pointer local variable destroyed immediately. it's not different had written:
t* b_row_to_array(b_row r) { t = { ... }; homecoming &a; // <== destroyed, have dangling pointer }
if want work, need a
last. means either allocating it:
unsigned* b_row_to_array(b_row r) { unsigned* = new unsigned[5]; ... homecoming a; }
or returning value:
std::array<unsigned, 5> b_row_to_array(b_row r);
c++ unit-testing pointers
Comments
Post a Comment