Corrupted vector entries with LPCWSTR vector

后端 未结 2 948
无人及你
无人及你 2021-01-28 18:07

I ahve the following piece of code. I get a correctly filled vector. But I am unable to print or use the vector contents which are file names from a directory. As soon as I do e

相关标签:
2条回答
  • 2021-01-28 18:37

    search_data.cFileName is a pointer to memory controlled by the FindFirstFile/FindNextFile iterator interface; you cannot store this pointer value as the pointed-to memory could change from iteration to iteration (or even be freed after the iteration completes).

    Instead, you must make a copy of the string to put in your vector, e.g. using wcsdup. Even better, define your vector as a vector<wstring>, so that push_back(search_data.cFileName); creates a wstring with the contents of search_data.cFileName.

    0 讨论(0)
  • 2021-01-28 18:45

    Probably that's happening because you pass local variable to push_back(). I'm not sure here, but what could happen here: push_back expects object of type LPCWSTR, while you passing char* instead. I don't know, how this conversion is done, but probably the pointer is just copied, and the value of this pointer becomes invalid whenyou return from the function - try explicit copying the strings before passing them to push_back.

    0 讨论(0)
提交回复
热议问题