c++ - Passing pointer to dynamically allocated array by copy to function has unexpected result -
i messing around passing pointers functions wrap head around how works , came across behavior unexpected. have following code:
#include <iostream> #include <string> #include <fstream> #include <sstream> #include <cmath> #include <iomanip> using namespace std; struct t { string x; string y; }; void foo(t*); int main() { t* ts = new t[2]; ts[0].x = "t1.x"; ts[0].y = "t1.y"; ts[1].x = "t2.x"; ts[1].y = "t2.y"; foo(ts); cout << ts[0].x << endl; } void foo(t* s) { delete[] s; s = new t[2]; s[0].x = "foo.x"; s[1].y = "foo.y"; }
the output here, interestingly enough, "foo.x"
. expected since inside of foo
, s
copy of pointer ts
when delete[] s
delete[] ts
both point same address. s = new t[2];
should have no effect on ts
. after foo
returns, should no longer have access s
or array points , ts
should point knows where. missing somehthing?
note: test project made write , erase blocks of code test different concepts. includes , using namespace std ease of use, , not code writing sort of practical use, purely educational. also, using ms vs 2013.
try changing foo() , see result:
void foo(t* s) { delete[] s; // additional memory allocation t* u = new t[2]; s = new t[2]; s[0].x = "foo.x"; s[1].y = "foo.y"; }
by adding memory allocation, moved s
location in memory, not anymore overlapping ts
. otherwise, s
allocated @ same location ts
resided.
as pointed out in comments, observing undefined behavior, should no means rely on. example above illustrates pretty well.
Comments
Post a Comment