LPSTR strcat - access violation

Started by
2 comments, last by zoggo 19 years, 2 months ago
LPSTR szBuffer = "mary had a little "; lstrcat(szBuffer,"lamb"); cout<<szBuffer<<endl; causes an access violation can someone please explain why...?
Advertisement
LPSTR is a pointer to a static string. When you try to add on more to it, it overwrites system memory, thus causing it to crash since it does not have enough space allocated. What you would need to do is use a character array or std::string. Here is an alternative solution example. Here is the MSDN reference to lstrcat.
i see

thank you v.much!
Also, bare in mind that string literals (strings defined with ") are defined to be const by the C++ standard and are allowed to be placed in read-only memory. So even if you wrote within the bounds of the string, the behaviour is undefined and quite possibly a good ol' fashioned access violations.

VC 6 treats string literals as non const and will allow all sorts of peculier things that it shouldn't. The following code works under VC 6 but crashed on VC 2003 and DevC++ (GCC)

	char* t = "Hello!";	t[ 0 ] = 0;


Note that unlike most illeagal cv-qualifier conversions, string literals are automatically converted to the non-const version for compatibility.

This topic is closed to new replies.

Advertisement