Let’s say I have a loop like this:
vector<shared_ptr<someStruct>> vec;
int i = 0;
while (condition)
{
i++
shared_ptr<someStruct> sps(new someStruct());
WCHAR wchr[20];
memset(wchr, i, 20);
sps->pwsz = wchr;
vec.push_back(sps);
}
At the end of this loop, I see that for each sps element of the vector, sps->pwsz is the same. Is this because I’m passing a pointer to memory allocated in a loop, which is destructed after each iteration, and then refilling that same memory on the next iteration?
I don’t think this code does what you expect it to. You probably want
wchrcreated on the heap or as a member ofsomeStruct.wchris allocated on the stack and gets freed on each iteration. The stack location will be the same on each iteration (probably the same).Each of your smart pointers contains a pointer to that invalid memory address.
After your while loop all of your smart pointers point to that same invalid already freed address. The address was re-used and freed on each iteration.