Sign in to follow this  

Stack around the variable was corrupted?

This topic is 4339 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

I just ran my game and am getting this message from Vis C++ 2005 Express. "Run-Time Check Failure #2 - Stack around the variable 'ptr' was corrupted." I've never seen anything like this before. Can someone tell me what I've done wrong? You can follow the steps 1, 2, 3, 4. // step 1 STRINGC2& STRINGC2::operator += (const char x) { // if (x == 0) return *this; char ptr[1]; // max is 1 digit ptr[0] = x; ptr[1] = '\0'; *this += ptr; // off to step 2 and back return *this; // step 4 crash } // step 2 STRINGC2& STRINGC2::operator += (const char* x) { IncrementPrivate (x); // off to step 3 return *this; } // step 3 void STRINGC2::IncrementPrivate (const char* str) { int len1, len2; char* new_str; len1 = strlen (Str); len2 = strlen (str); new_str = new char [len1 + len2 + 1]; strcpy_s (new_str, len1 + len2 + 1, Str); strcat_s (new_str, len1 + len2 + 1, str); FREE_ARRAY (Str); Str = new_str; }

Share this post


Link to post
Share on other sites

char ptr[1]; // max is 1 digit

ptr[0] = x;
ptr[1] = '\0';


In the first line you reserve 1 char on the stack. In the third line, you then access the 2nd character to put in a 0-character.
So, your fix is: char ptr[2];

Share this post


Link to post
Share on other sites
Quote:
Original post by Davaris
"Run-Time Check Failure #2 - Stack around the variable 'ptr' was corrupted."

char ptr[1]; // max is 1 digit
ptr[0] = x;
ptr[1] = '\0'; <-- Error here

Share this post


Link to post
Share on other sites
Quote:
Original post by Davaris
I just ran my game and...

This implies that this is not just for learning but you are actually trying to use your own string class in a real application. Why are you not using std::string or a trivial wrapper around std::string (if you desire additional functionality and your coding standards do not allow you to use non-member functions for such functionality)?

Enigma

Share this post


Link to post
Share on other sites

This topic is 4339 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this