How to end up with a pointer to 0xCCCCCCCC - c++

The program I'm working on crashes sometimes trying to read data at the address 0xCCCCCCCC. Google (and StackOverflow) being my friends I saw that it's the MSVC debug code for uninitialized stack variable. To understand where the problem can come from, I tried to reproduce this behavior: problem is I haven't been able to do it.
Question is: have you a code snippet showing how a pointer can end pointing to 0xCCCCCCCC?
Thanks.

int main()
{
int* p;
}
If you build with the Visual C++ debug runtime, put a breakpoint in main(), and run, you will see that p has a value of 0xcccccccc.

Compile your code with the /GZ compiler switch or /RTCs switch. Make sure that /Od switch is also used to disable any optimizations.
s
Enables stack frame run-time error checking, as follows:
Initialization of local variables to a nonzero value. This helps identify bugs that do not appear when running in debug mode. There is a greater chance that stack variables will still be zero in a debug build compared to a release build because of compiler optimizations of stack variables in a release build. Once a program has used an area of its stack, it is never reset to 0 by the compiler. Therefore, subsequent, uninitialized stack variables that happen to use the same stack area can return values left over from the prior use of this stack memory.
Detection of overruns and underruns of local variables such as arrays. /RTCs will not detect overruns when accessing memory that results from compiler padding within a structure. Padding could occur by using align (C++), /Zp (Struct Member Alignment), or pack, or if you order structure elements in such a way as to require the compiler to add padding.
Stack pointer verification, which detects stack pointer corruption. Stack pointer corruption can be caused by a calling convention mismatch. For example, using a function pointer, you call a function in a DLL that is exported as __stdcall but you declare the pointer to the function as __cdecl.

I do not have MSVC, but this code should produce the problem and compile with no warnings.
In file f1.c:
void ignore(int **p) { }
In file f2.c:
void ignore(int **p);
int main(int c, char **v)
{
int *a;
ignore(&a);
return *a;
}
The call to ignore makes it look like a might be initialized. I doubt the compiler will warn in this case, because of the risk that the warning might be a false positive.

How about this? Ignore the warning that VC throws while running.
struct A{
int *p;
};
int main(){
A a;
cout << (void *)a.p;
}

Related

Why my visual c++ is not triggering stack corruption error in situation of stack corruption

I have following code..
#include "stdafx.h"
#include <stdlib.h>
#include <conio.h>
struct data
{
int d;
};
void main()
{
data *p=(data*)malloc(sizeof(data));
p->d=10;
free(p);
p->d=10;
_getch();
}
I expect a stack corruption error while running the code but Visual studio fires nothing...even after freeing p...
It must trigger error of accssesing unreferenced pointer...But still it continues reading and writing...Why this is happening also I have this following code..
int a[]={1,2,3};
void main()
{
a[5]=100;
_getch();
}
here I am accssesing array out of bound, but still it continues..
It never happned before.I cant say whats wrong here?
The behaviour of the second p->d=10; is undefined. Not crashing is a manifestation of that undefined behaviour. (You may well find that free doesn't actually give the memory back to the operating system in your particular case.)
a[5]=100; is undefined too. Again, you might find that the C++ runtime library / operating system have allocated memory in excess of 3 ints.
Notwithstanding (1) and (2), your program is undefined as you need to use int main(). Again, permitting compilation and runtime behaviour consistent with that you'd get with int main() is a manifestation of undefined behaviour.
Terminology: STACK and HEAP are not the same thing.
Stack is used for static memory allocation: char foo[100];
Heap is used for dynamic memory allocation: char * foo = malloc(100);
It has been a few years since I used visual C++. I seem to recall it has compile and maybe link time options to check for memory issues.
At runtime, the C/C++ runtime system asks for memory from the operating system, it gets the memory in large blocks, then the C/C++ runtime code slices it up as needed. When you step outside of that block, you may get run time errors. You may randomly get other errors.
When function2() correctly uses that part of the block of memory that function1() has corrupted, then you may get weird run time errors as you have corrupted the stack or heap. When no other part of your program uses that same memory you have corrupted, then it is likely you will not see any error. You code still has that bug, however it does not show up until another part of your code or the C/C++ runtime noticed you stepped on its variables.

Debug unintended use of memory "belonging" to parent function

Suppose I have a function foo (in C/C++) that is called from a given software tool.
Function foo is only allowed to write memory that has been allocated by foo or one of the functions called by foo, but not to write to memory that has been allocated by the functions that have been executed before calling foo.
I have the strong suspicion that at some place foo writes to memory it is not allowed to.
Is there a way to systematically debug this behavior? Maybe some fancy flag to valgrind?
The Valgrind manual has some Valgrind functions that your program can call.
It looks like VALGRIND_MAKE_MEM_NOACCESS may be what you want.
You could use a custom allocator (Boost Pool comes to mind) to make sure all your memory that you want to 'protect' is contiguously allocated.
Next, set a hardware breakpoint when any data in that memory region is changed.
I'd write a GDB script that sets a breakpoint on your function, then sets a hardware watch on the memory you suspect is being altered, then continues.
If function foo is modifying that memory the hardware watch will trigger on that instruction doing it.
The GDB script might look like:
break foo
commands
up
watch array
down
continue
end
I didn't test that and it may need tweaking, especially the watch expression. You might be limited to watching only one array element. I believe hardware watchpoints can actually watch only one integer size block: 4 bytes on 32 bit or 8 bytes on 64 bit.
The only way foo() can write to the memory outside its scope is if that memory is global, i.e. extern variable, or if foo() had one or more arguments which were meant to be read only but somehow they got modified.
To verify if the calling arguments are getting modified, you can create a structure to hold the arguments and just before returning compare original with saved arguments.
struct foo_args {
int a;
char *b;
};
void
foo(int a, char *b)
{
struct foo_args args;
args.a = a
args.b = strdup(b);
/* The rest of the foo() code. */
if (args.a != a || strcmp(args.b, b) != 0) {
printf("error - args got modified\n");
}
free(args.b);
}
If the above doesn't catch it, then the likely scenario is that either global, stack or heap memory is getting corrupted.
To have valgrind run the tool may not be practical, in which case you will need to create a 'wrapper' for foo() and ensure using valgrind or something similar that it is not doing what it is not supposed to do. The other option is to use a debugging library that tracks/monitors memory usage and flags memory errors as they occur.

General way of solving Error: Stack around the variable 'x' was corrupted

I have a program which prompts me the error in VS2010, in debug :
Error: Stack around the variable 'x' was corrupted
This gives me the function where a stack overflow likely occurs, but I can't visually see where the problem is.
Is there a general way to debug this error with VS2010? Would it be possible to indentify which write operation is overwritting the incorrect stack memory?
thanks
Is there a general way to debug this error with VS2010?
No, there isn't. What you have done is to somehow invoke undefined behavior. The reason these behaviors are undefined is that the general case is very hard to detect/diagnose. Sometimes it is provably impossible to do so.
There are however, a somewhat smallish number of things that typically cause your problem:
Improper handling of memory:
Deleting something twice,
Using the wrong type of deletion (free for something allocated with new, etc.),
Accessing something after it's memory has been deleted.
Returning a pointer or reference to a local.
Reading or writing past the end of an array.
This can be caused by several issues, that are generally hard to see:
double deletes
delete a variable allocated with new[] or delete[] a variable allocated with new
delete something allocated with malloc
delete an automatic storage variable
returning a local by reference
If it's not immediately clear, I'd get my hands on a memory debugger (I can think of Rational Purify for windows).
This message can also be due to an array bounds violation. Make sure that your function (and every function it calls, especially member functions for stack-based objects) is obeying the bounds of any arrays that may be used.
Actually what you see is quite informative, you should check in near x variable location for any activity that might cause this error.
Below is how you can reproduce such exception:
int main() {
char buffer1[10];
char buffer2[20];
memset(buffer1, 0, sizeof(buffer1) + 1);
return 0;
}
will generate (VS2010):
Run-Time Check Failure #2 - Stack around the variable 'buffer1' was corrupted.
obviously memset has written 1 char more than it should. VS with option \GS allows to detect such buffer overflows (which you have enabled), for more on that read here: http://msdn.microsoft.com/en-us/library/Aa290051.
You can for example use debuger and step throught you code, each time watch at contents of your variable, how they change. You can also try luck with data breakpoints, you set breakpoint when some memory location changes and debugger stops at that moment,possibly showing you callstack where problem is located. But this actually might not work with \GS flag.
For detecting heap overflows you can use gflags tool.
I was puzzled by this error for hours, I know the possible causes, and they are already mentioned in the previous answers, but I don't allocate memory, don't access array elements, don't return pointers to local variables...
Then finally found the source of the problem:
*x++;
The intent was to increment the pointed value. But due to the precedence ++ comes first, moving the x pointer forward then * does nothing, then writing to *x will be corrupt the stack canary if the parameter comes from the stack, making VS complain.
Changing it to (*x)++ solves the problem.
Hope this helps.
Here is what I do in this situation:
Set a breakpoint at a location where you can see the (correct) value of the variable in question, but before the error happens. You will need the memory address of the variable whose stack is being corrupted. Sometimes I have to add a line of code in order for the debugger to give me the address easily (int *x = &y)
At this point you can set a memory breakpoint (Debug->New Breakpoint->New Data Breakpoint)
Hit Play and the debugger should stop when the memory is written to. Look up the stack (mine usually breaks in some assembly code) to see whats being called.
I usually follow the variable before the complaining variable which usually helps me get the problem. But this can sometime be very complex with no clue as you have seen it. You could enable Debug menu >> Exceptions and tick the 'Win32 exceptions" to catch all exceptions. This will still not catch this exceptions but it could catch something else which could indirectly point to the problem.
In my case it was caused by library I was using. It turnout the header file I was including in my project didn't quite match the actual header file in that library (by one line).
There is a different error which is also related:
0xC015000F: The activation context being deactivated is not the most
recently activated one.
When I got tired of getting the mysterious stack corrupted message on my computer with no debugging information, I tried my project on another computer and it was giving me the above message instead. With the new exception I was able to work my way out.
I encountered this when I made a pointer array of 13 items, then trying to set the 14th item. Changing the array to 14 items solved the problem. Hope this helps some people ^_^
One relatively common source of "Stack around the variable 'x' was corrupted" problem is wrong casting. It is sometimes hard to spot. Here is an example of a function where such problem occurs and the fix. In the function assignValue I want to assign some value to a variable. The variable is located at the memory address passed as argument to the function:
using namespace std;
template<typename T>
void assignValue(uint64_t address, T value)
{
int8_t* begin_object = reinterpret_cast<int8_t*>(std::addressof(value));
// wrongly casted to (int*), produces the error (sizeof(int) == 4)
//std::copy(begin_object, begin_object + sizeof(T), (int*)address);
// correct cast to (int8_t*), assignment byte by byte, (sizeof(int8_t) == 1)
std::copy(begin_object, begin_object + sizeof(T), (int8_t*)address);
}
int main()
{
int x = 1;
int x2 = 22;
assignValue<int>((uint64_t)&x, x2);
assert(x == x2);
}

Why Access Violation for cout and Stack Overflow for printf

I wanted to know why Access Violation occurs for cout and Stack Overflow for printf in the following two code snippets.
I wanted to know why Access Violation for the first code instead of the Stack Overflow.
First code which I get Access Violation :
void Test();
void Test()
{
static int i = 0;
cout << i++ << endl;
Test();
}
int main()
{
Test();
return 0;
}
Second code which I get Stack Overflow :
void Test();
void Test()
{
static int i = 0;
printf("%d\n", i++);
Test();
}
int main()
{
Test();
return 0;
}
I assume you understand that both functions crash due to exhaustion of the stack after an attempt at infinite recursion. I think what you are asking is: why would the cout example not crash with "Stack Overflow" also?
I do not think the answer has to do with the compiler's detection of tail recursion. If the compiler optimized the recursion away, neither example should crash.
I have a guess as to what is going on. "Stack Overflow" exception is implemented in some cases (e.g., Windows) with a single Virtual Memory "guard page" allocated at the end of the stack. When a stack access hits this guard page a special exception type is generated.
Since the Intel small-granularity page is 4096 bytes long, the guard page stands guard over a range of memory that size. If a function call allocates more than 4096 bytes of local variables, it is possible that the first stack access from it will actually stretch beyond the guard page. The next page can be expected to be unreserved memory, so an access violation would make sense in that case.
Of course you don't explicitly declare any local variables in your example. I would assume that one of the operator<<() methods allocates more than a page of local variables. In other words, that the Access Violation occurs near the beginning of an operator<<() method or some other part of the cout implementation (temporary object constructors, etc.)
Also, even in the function you wrote, the operator<<() implementations are going to need to create some storage for intermediate results. That storage is probably allocated as local storage by the compiler. I doubt it would add up to 4k in your example, though.
The only way to really understand would be to see a stack trace of the access violation to see what instruction is triggering it.
Got a stack trace of the access violation and a disassembly around the area of the faulting opcode?
If you are using the Microsoft C compiler, another possibility is that printf() and your own function were compiled with /Ge and operator<<() was not, or that only your function was compiled with /Ge and factors similar to those described above coincidentally cause the behavior you see -- because in the printf() example the crash happens while your function is being called and in the operator<<() case while you are calling the library.
Both recursive functions will never stop.
It seems that in the second case, no tail optimization is done by the compiler, thus the stack overflow.
Both functions trigger a stack overflow on my machine. I am compiling it with MS Visual Studio 2005. Maybe you should specify your platform & compiler, that will help to investigate...
Maybe you compile something in the debug mode and your "cout" implementation includes some checkups, that cannot be performed due to the stack corruption? Maybe your compiler generated the code, that tries to recover from stack overflow and pops an invalid return address? Maybe you are running it on the mobile device? Hard to say without knowing the platform and the compiler.
Infinite recursive call is for the stack overflow. As for the access violation... it really depends on the implementation of STL streams. You need to take a look on the source code of streams to find out...
Though most people misunderstood your question, the answer is in there.
The second example ends with stack overflow because every function call is pushing a frame onto the stack. Eventually, it gets too big. I agree with Cătălin Pitiș, that it'd be hard to know why the streams example is ending with an access violation without looking at the source.
this remembers me of the problem of the stack being corrupted and the debugger not catching the failing program crashing

User Breakpoint from nowhere

I have some code in MS VC++ 6.0 that I am debugging. For some reason, at this certain point where I am trying to delete some dynamically allocated memory, it breaks and I get a pop up message box saying "User Breakpoint called from code at blah blah".. then the Disassembly window pops up and I see
*memory address* int 3
The odd thing is, there is NOWHERE in the code that I am calling an assembly instruction like this (I think asm int 3 is a hardware break command for x86?)..
what could be causing this?
EDIT: ANSWER: My code was "walking off the end" of an array, but only in the locations marked by Visual Studio debug with 0xFDFDFDFD, which is called a NoMan'sLand fence.. I think its also called an Off-by-one error.. This array was unrelated to the point where i was freeing the memory when the error was occuring. Which made it harder to spot.. :(
You're probably hitting code in the debug heap routines that have found heap corruption.
What does the call stack look like when you've hit the Int 3?
Edit: Based on the stack trace in your comments, the routine _CrtIsValidHeapPointer() is saying that the pointer being freed is bad. Here's the snippet of code from MSVC's DBGHEAP.C source:
/*
* If this ASSERT fails, a bad pointer has been passed in. It may be
* totally bogus, or it may have been allocated from another heap.
* The pointer MUST come from the 'local' heap.
*/
_ASSERTE(_CrtIsValidHeapPointer(pUserData));
pUserData would be the value of the pointer you're deleteing.
(I think asm int 3 is a hardware break
command for x86?
It is. It's called "hardware breakpoint". If you're using the VS debugger with the project source code, it's just like a breakpoint (but in the code). Since vs2005, if your application is launched without any debugger, the application will simply crash, like if it launched an unmanaged exception.
In lot of company, there is a simple macro used to add that breakpoint in the code. That can replace asserts and exceptions in some (hard and rare) cases :
#define BREAKPOINT __asm { int 3; }
BREAKPOINT;
See :
http://msdn.microsoft.com/en-us/library/45yd4tzz(VS.80).aspx
http://www.highprogrammer.com/alan/windev/visualstudio.html
So i suggest looking for some Macro or object doing this, or maybe it appen in a module (dll/lib) that you don't have the code of?