tags:

views:

207

answers:

3

I know that Visual Studio under debugging options will fill memory with a known value. Does g++ (any version, but gcc 4.1.2 is most interesting) have any options that would fill an uninitialized local POD structure with recognizable values?

struct something{ int a; int b; };
void foo() {
    something uninitialized;
    bar(uninitialized.b);
}

I expect uninitialized.b to be unpredictable randomness; clearly a bug and easily found if optimization and warnings are turned on. But compiled with -g only, no warning. A colleague had a case where code similar to this worked because it coincidentally had a valid value; when the compiler upgraded, it started failing. He thought it was because the new compiler was inserting known values into the structure (much the way that VS fills 0xCC). In my own experience, it was just different random values that didn't happen to be valid.

But now I'm curious -- is there any setting of g++ that would make it fill memory that the standard would otherwise say should be uninitialized?

+1  A: 

I don't believe g++ will detect all cases like this, but Valgrind certainly will.

Billy ONeal
Yes, other analysis tools seem to be the solution. Seemed like something the compiler could arrange, but not too surprising if it doesn't.
Bob Lied
+2  A: 

Any C++ comiler can initialize any POD type to its "zero" value using the syntax:

int i = int();
float f = float();
MyStruct mys = MyStruct();
// and generally:
T t = T();

If you want to talk about debugging that's something else...

(By the way, I think VS had all uninitialized memory initialized to 0xCC when in "debug mode, so that no matter where you jump (e.g. call a bad function pointer) that's doesn't happen to be actual program code/data int3 is raised.)

conio
Or, for those who long to make C++ look like Lisp, `T t((T()))` :-)
James McNellis
@James: You're absolutely right, but this syntax puts me in a dilemma. I don't know what hurts more looking at it - my eyes or my heart. :)
conio
@conio: Yes, it *can* initialize, but it didn't, so I guess I am really slanted toward debugging help. Sounds like the solution lies outside of g++, though (valgrind et.al).
Bob Lied
+2  A: 

I don't think such option/feature exists in gcc/g++.

For instance, all global (and static) variables reside in the .bss section, which is always initialised to zeroes. However, uninitialised ones are put in a special section within the .bss, for sake of compatibility.

If you want the them to be zeroed too, you can pass -fno-common argument to the compiler. Or, if you need it on a per-variable basis, use __attribute__ ((nocommon)).

For heap, it's possible to write your own allocator to accomplish what you described. But for stack, I don't think there's an easy solution.

jweyrich
I didn't think the feature existed either, but the gcc manual is long and deep, and I've been surprised by what's hidden in there before.
Bob Lied