Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Run-Time Check Failure #2 - Stack around the variable was corrupted

Status
Not open for further replies.

RichardF

Programmer
Oct 9, 2000
239
0
0
GB
Hi,

Code:
int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	char cPath[MAX_PATH];

	ZeroMemory(cPath,MAX_PATH);
	GetModuleFileName(NULL,cPath,MAX_PATH);

	// cPath = "c:\Documents and Settings\rich\My Documents\Visual Studio Projects\C++\cTest2\Debug\cTest2.exe"

	strcpy_s(strrchr(cPath,'\\')+1,MAX_PATH,"File.tmp");

	// cPath = "c:\Documents and Settings\rich\My Documents\Visual Studio Projects\C++\cTest2\Debug\File.tmp"

	FILE *fp = NULL;

	fopen_s(&fp,cPath,"w");
	fputs("hello\n",fp);

	fclose(fp);

	return 0;
} // <-- message appears here

The above code cause a Runtime check failure #2. (The file is getting written to though).

Does anyone know what is causing this ?

Thanks in advance.
Rich.

WinXP SP2, MSVC 2005.
 
I'm not sure if this is the cause of your problem, but it's definitely wrong:
Code:
strcpy_s(strrchr(cPath,'\\')+1,MAX_PATH,"File.tmp");
strrchr(cPath,'\\') is returning a pointer to somewhere in the cPath string, but then you tell strcpy_s() that the string has MAX_PATH bytes from that location, which could cause an array overflow.

You might fix it like this:
Code:
char* pszLastBS = strrchr( cPath, '\\' ) + 1;

if ( pszLastBS == NULL )
{
   // No '\' was found, handle this error condition here.
}

strcpy_s( pszLastBS, MAX_PATH - (pszLastBS - cPath), "File.tmp" );
or even better would be to use an STL string instead of a char array...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top