Something wrong in the code



1
2
3
4
5
6
7
void File::Write(const char* buf,const char* pErrorParameter1,const char* pErrorParameter2,const char* pErrorParameter3)

///some operation
char* pChar = (char*)(strstr(buf," '%1' "));
			if(pChar != NULL)
				strcat((char*)buf,(char*)pErrorParameter1);
			mOutputFileHandle<<buf<<"\n";


Where mOutputFileHandle is handle to a file .

When my program comes out of this function then it throws an exception.

Can anyone please help me?
Last edited on
You are casting away constness and writing to buf anyway. That sounds dangerous, but I don't
know how you are calling Write() [ie, what is the first parameter a pointer to... writable
memory? Is the caller expecting their buffer to change, since the parameter is declared const?]
Hi Smith,
thanks for replying. can u plz refer to the following topic and can u plz help me.
http://www.cplusplus.com/forum/general/18986/
The problem is as I described.

Look at all the places you call File::Write().

_tmain():26, ThrowException():13, ThrowException():16.

In all three places, you are passing a const char* to File::Write. (string::c_str() returns a const char*; you
must not change what it points to, and in _tmain(), although you've declared buf to be a char*, because it is a
string literal, it is effectively also a const char*).

const char* means don't write to the string. But your File::Write() function casts away the constness and writes
to it anyway, and this is why you are crashing.

As a general rule, a good design very rarely ever should use const_cast. A proper File::Write() implementation
would make a secondary buffer on the stack and write to it rather than to its (buf) parameter.
hi jsmith,
thanks that solves the problem.

instead of creating the buffer, i have assigned to a string object and then did the operation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void File::Write(const char* buf,const char* pErrorParameter1,const char* pErrorParameter2,const char* pErrorParameter3)
{
	if(IsFileAlreadyOpen())
	{
		
		if(!IsErrorFlagSet())
		{
			mOutputFileHandle<<buf<<"\n";
		}
		else
		{
			std::string str = buf;
			std::string str2 = "%1";
			str.replace(str.find(str2),str2.length(),pErrorParameter1);
			mOutputFileHandle<<str.c_str()<<"\n";
			
		}
		mOutputFileHandle.close();
	}
	

}
Topic archived. No new replies allowed.