Have a situation with my code, where it appears the stringstream object is not being cleared.
Here is my code, this code will set an interprocess shared variable,
The code is simplified to illustrate my problem, and all other variables are there to aid in that, for instance, the ints in this code are not the types I am using in my app which are uintptr. But the problem remains the same.
int _tmain()
{
TCHAR szName[]=TEXT("MyFileMappingObject");
HANDLE hMapFile;
LPCTSTR pBuf;
hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE,
NULL,
PAGE_READWRITE,
0,
BUF_SIZE,
szName);
if (hMapFile == NULL)
{
_tprintf(TEXT("Could not create file mapping object (%d).\n"),
GetLastError());
_getch();
return 1;
}
pBuf = (LPTSTR) MapViewOfFile(hMapFile,
FILE_MAP_ALL_ACCESS,
0,
0,
BUF_SIZE);
if (pBuf == NULL)
{
_tprintf(TEXT("Could not map view of file (%d).\n"),
GetLastError());
CloseHandle(hMapFile);
_getch();
return 1;
}
stringstream ss (stringstream::in | stringstream::out | stringstream::trunc);
int Int = 55525;
ss << Int;
string s = ss.str();
const char * p = s.c_str();
ss.clear(); // here I am trying to clear the buffer
CopyMemory((PVOID)pBuf, p, (_tcslen(p) * sizeof(TCHAR)));
//at this point the shared variable read from other app is "55525"
_getch();
int Int2 = 44425;
ss << Int2;
string s2 = ss.str();
const char * p2 = s2.c_str();
ss.clear();
CopyMemory((PVOID)pBuf, p2, (_tcslen(p2) * sizeof(TCHAR)));
//at this point the shared variable read from other app is "5552544425"
//when I was expecting it to be "44425"
_getch();
UnmapViewOfFile(pBuf);
CloseHandle(hMapFile);
return 0;
}
I am assuming it's the stringstream, but of course it could be a buffer problem.
The only two common vars used are ss and pBuf.
I have use this method of sharing between process in a different fashion, and not had this problem, which is why I'm thinking it is the ss.
I'd appreciate if an eye cast over my code for any glaring errors I may have made.
Or indeed any other comments or advice.