VC ++ 2010 issues

Run-Time Check Failure # 2 - Stack around the variable 'x' was corrupted.

Occurs because of the string "pchar ++" (increasing the pointer value by 1), but this is also a valid operation. What to do to not give an error?

#include <iostream> using namespace std; void func(char *pchar); int main() { char *pchar, x; pchar = &x; *pchar = 'a'; func(pchar); cout << *pchar; } void func(char *pchar) { char *pch; *pchar = 'b'; pchar++; *pchar = 'c'; } 
  • @ Art, To format the code, select it with the mouse and click on the button 101010 of the editor. - Nicolas Chabanovsky
  • Do not write where it is not. pchar refers to the variable char x . Write there 'b' is normal. Write in the next for x bytes 'c' - spoil something. vc ++ takes offense and starts to swear. - alexlz
  • But this is an allowed operation. - Art
  • What operation is allowed? Increase pchar? Yes. Writing to memory (on the stack - variable x - local) outside the variable x, hz. where? Not. And anyway, what's this? Laboratory work on "stack failure"? - alexlz
  • What does it mean "everything works"? This means that you are spoiling something that does not manifest itself during the operation of your program. This is temporary. If you do not write carefully - someday will affect. Such errors are sometimes very difficult to detect. (Well, about new you have already written). And further. The phrase "memory allocated for a pointer" is incorrect in this context. In your case, 4b is allocated for the pchar pointer (if the system is 32 bits) in the stack frame reserved by the main procedure. This is the memory that the pointer itself takes. - alexlz

3 answers 3

You move to the area, further than allotted to the variable and ask why an error occurs? Imagine that a neighbor breaks through the wall to you, just drink tea ... The variable that is in the stack and you are climbing feels the same way!

Sori for the pun.

By the way, if you want to play around with ++ applies to pointers, do something like:

 char b[] = new char[200]; b++; 
  • This is not C #. It should be like this: char * b = new char [200]; - gammaker
  • Oh, litter ... For a long time did not write on pluses :). - Jakeroid

When you write pchar++ you move beyond the allocated (allocated) under pchar memory and invade the area that is occupied by the variable x .

To prevent this from happening, you need to allocate under pchar not 1 element, but at least 2

 pchar=new char[2]; 

then pchar ++ will point to pchar [1]

  • Just do not invade, and leave. See before func (pchar) pchar set to x. Apparently in the original func () the pointer changes the value of x from 'a' to 'b'. To “ enhance the effect, ” the author decided to add 'c' to the next byte, and fell ... You are @Barmaley, consider another case in your answer (apparently methodologically correct, but different). - avp

Try this:

 char *pchar; pchar = new char[2]; *pchar='a'; *pchar='b'; pchar++; *pchar='c';