When the function involves reallocation, I found some compilers may save the address before the function call. It leads the return value stored in the invalid address.
There is an example to explain behavior in above description.
#include <stdio.h>
#include <vector>
using namespace std;
vector<int> A;
int func() {
A.push_back(3);
A.push_back(4);
return 5;
}
int main() {
A.reserve(2);
A.push_back(0);
A.push_back(1);
A[1] = func();
printf("%d\n", A[1]);
return 0;
}
There are some common C++ compiler, and the test result as follows.
- GCC(GNU Compiler Collection): Runtime Error or output
1
- Clang: output
5
- VC++: output
5
Is it undefined behavior?