0

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

Robert
  • 13
  • 1

2 Answers2

0

You shouldn't be storing pointers inside the vector to begin with, because it requires that you manually manage the memory allocated to the pointers. The vector will only manage its own memory (which includes the pointers) but not what these point to.

Use vector<string> to store strings.

Ulrich Eckhardt
  • 662
  • 6
  • 14
  • Avoid raw pointers, as a very general advise. In the case of LPCSTR, use a string instead. In the case of structures use the structure as parameter for vector. Of course this requires that the struct itself keeps track of its own resources, so don't store pointers in it that represent ownership. – Ulrich Eckhardt Oct 15 '15 at 12:32
0

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.

doctorlove
  • 18,872
  • 2
  • 46
  • 62