Click here to Skip to main content
15,906,329 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
<pre>DWORD errorNo = 0;
template <typename TYPE>
bool read(HANDLE hPipe,TYPE &data)
{
	DWORD size=sizeof(TYPE),dwBytesRead=0;
	bool ret=ReadFile(hPipe,&data,size,&dwBytesRead,NULL);
	errorNo = GetLastError();
	return ret;
}
bool readString(HANDLE hPipe,string &str)
{
	DWORD size,dwBytesRead=0;
	char *c;
	bool ret=read(hPipe,(int &)size);
	if(ret&&size>0  )
	{
		c=new char[size+1];
		ret=ReadFile(hPipe,c,size,&dwBytesRead,NULL);  //throw 0xC0000005 
		c[size]='\0';
		str= string(c);
	}
	return ret;
}



the ReadFile function throw 0xC0000005 error, because read function cann't get the right size,In most cases, the right size can be obtained. When the program runs for hundreds of thousands of times, there is some times a failure to get the right size and cause errors.
how to solve this question

What I have tried:

use GetLastError() to get error number,but the number is zero.
Posted
Updated 5-Apr-18 23:23pm

ReadFile[^] should not (and I'm pretty sure it does not) throw anything. It may return FALSE (and then you have to immediately call GetLastError to get more info).

Please note, your code is bad: you are continuosly allocating memory that is NEVER released.
 
Share this answer
 
The only possible reasons that come to my mind are when size is UINT_MAX (0xFFFFFFFF) or reading the string length is interrupted by a write operation completion on the write end of the pipe.

To avoid the latter, use a loop for reading:
C++
bool read(HANDLE hPipe, TYPE &data)
{
    DWORD size = sizeof(TYPE);
    bool ret = true;
    char *buf = reinterpret_cast<char*>(&data);
    do
    {
        DWORD dwBytesRead = 0;
        ret = ReadFile(hPipe, buf, size, &dwBytesRead, NULL);
        buf += dwBytesRead;
        size -= dwBytesRead;
    } while (ret && size);
    return ret;
}


Additional notes:

Why do you cast here?
bool ret=read(hPipe,(int &)size);
When casting is really necessary (which it isn't here), use C++ casts and not C casts.

You forgot to delete c so that you have a memory leak.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900