Jump to content
  • Advertisement
Sign in to follow this  
Davaris

Stack around the variable was corrupted?

This topic is 4618 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
Advertisement
One thing i can see is the incrementing of 'this'. This looks dangerous to me.

Dave

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!