-Error read string characters

I have the following code:

for( CarsPool::CarRecord &record : recs->GetRecords()) { LVITEM item; item.mask = LVIF_TEXT; item.cchTextMax = 6; item.iSubItem = 0; item.pszText = (LPSTR)(record.getCarName().c_str()); //breakpoint on this line. item.iItem = 0; ListView_InsertItem(CarsListView, &item); item.iSubItem = 1; item.pszText = TEXT("Available"); ListView_SetItem(CarsListView, &item); item.iSubItem = 2; item.pszText = (LPSTR)CarsPool::EncodeCarType(record.getCarType()); ListView_SetItem(CarsListView, &item); } 

Information from Visual Studio Debugger is here:

enter image description here

Why can't a program read characters from a string?

The test showed me that it works as follows:

 MessageBox(hWnd, (LPSTR)(record.getCarName().c_str()), "Test", MB_OK); 
+6
source share
2 answers

getCarName Probably returns temporary. After the assignment, the temporary object is destroyed, and the item.pszText pointer points to invalid memory. You must ensure that the string object is valid during the call to ListView_InsertItem .

 std::string text(record.getCarName()); item.iSubItem = 0; item.pszText = const_cast<LPSTR>(text.c_str()); item.iItem = 0; ListView_InsertItem(CarsListView, &item); 

const_cast is an artifact of the fact that the Windows API uses the same structure to set and retrieve information. When you call ListView_InsertItem structure is unchanged, but there is no way to reflect this in the language.

+4
source

It looks like you are trying to use the value of a C ++ string in a C / Win32 call.

stdstring.c_str () is the right way to do this.

... BUT ...

You must strcpy () the string of the temp variable, and then call Win32 with the temp variable.

+3
source

Source: https://habr.com/ru/post/954361/


All Articles