• Advertisement
Sign in to follow this  

LPSTR strcat - access violation

This topic is 4724 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

LPSTR szBuffer = "mary had a little "; lstrcat(szBuffer,"lamb"); cout<<szBuffer<<endl; causes an access violation can someone please explain why...?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement