c++listpointersvectorlpcstr

The value of lpcstr was corrupt when push it on Vector or List


first of all excuse me for my bad English.

I have a function that generate a list of LPCSTR values, and i want to add all each of them to a list<LPCSTR> or vector<LPCSTR> , this is my sample code :

vector<LPCSTR> output={}; // or list<LPCSTR>

...

for (....)
{

    auto anItem = static_cast<LPSTR>(malloc(20));
    sprintf_s(anItem, 20, "string format", values...);
    output.push_back(anItem);

    /* The problem */
}   //free(anItem);  when i free the allocated memory of anItem then added item to output was being corrupt  !

If i free the allocated memory then data was being corrupt and else i have a huge unused memory ! If i decelerate the auto anItem = static_cast<LPSTR>(malloc(20)); before of the loop then all items added to the ouput was the value of current anItem!! And i have a list/vector of only one value !!!

please help to me !> thanks


Solution

  • If you have pointers you wish to put in a container, you have a choice.

    1. Just copy the pointer and then if what it points to gets deleted by another code path, you have a "dangling pointer" giving seemingly corrupted contents as you observe
    2. Use a smart pointer instead
    3. New your own pointer and copy over the contents and remember to clear this up at some point otherwise you have a memory hog.
    4. Copy the contents of the pointer

    For your case, you might find it easiest to copy the LPCSTR into a std::string and put those in a vector.