c++winapipointerstreeviewlparam

LPARAM keeps changing in TVITEM


I'm adding a bunch of items to a treeview, with a string stored in lParam, like this:

TVITEM tvi = {sizeof(TVITEM)};
tvi.mask = TVIF_TEXT | TVIF_PARAM;
tvi.pszText = const_cast<char *> (txt0.c_str());  // Display text
tvi.cchTextMax = sizeof(tvi.pszText);
tvi.lParam = (LPARAM) add0.c_str();  // A file path string

TVINSERTSTRUCT tvis;
tvis.item = tvi;
tvis.hParent = hti0;  // Some parent node

TreeView_InsertItem(tvw_filelist_, &tvis);

After I finish adding all of them, I come back and check (in a different function):

TVITEM tvi = {sizeof(TVITEM)};
char buf[200];
tvi.pszText = buf;
tvi.cchTextMax = 200;
tvi.hItem = htiTemp;  // htiTemp is the current node in the iteration
tvi.mask = TVIF_TEXT | TVIF_PARAM;

// Retrieve; address is stored in lParam.
TreeView_GetItem(tvw_filelist_, &tvi);

char out[200];
strcpy(out, "Checking: PSZTEXT: ");
strcat(out, tvi.pszText);
strcat(out, ". LPARAM: ");
strcat(out, (const char *) tvi.lParam);

...and the LPARAM has been reset to the value of the last item added.

So, if I add items one, two, three, four with similar lParam values, then after I check they all have lParam of four. (Sometimes, there's garbage values.)

There's obviously a problem here, and it's probably really easy to fix, but after several hours of experimenting I can't find what's wrong. Help!


Solution

  • tvi.lParam = (LPARAM) add0.c_str(); this is the problem. tvi.lParam is a pointer type.

    FROM MSDN :

    LPARAM This type is declared in WinDef.h as follows: typedef LONG_PTR LPARAM;

    what is a add0? I guess it is a local variable. If the function return, this add0 var will be deconstructed, and tvi.lParam is pointed to the inter buff of string add0, and now this inter buff is freed, so tvi.lParam points to the garbage.