Visual studio 2005: is there a compiler option to initialize all stack-based variables to zero? - visual-studio

This question HAS had to be asked before, so it kills me to ask it again, but I can't find it for all of my google and searching stackoverflow.
I'm porting a bunch of linux code to windows, and a good chunk of it makes the assumption that everything is automatically initialized to zero or null.
int whatever;
char* something;
...and then immediately doing something that may leave 'something' null, and testing against 'something'
if(something == NULL)
{
.......
}
I would REALLY like not to have to go back throughout this code and say:
int whatever = 0;
char* something = NULL;
Even though that is the proper way to deal with it. It's just very time consuming.
Otherwise, I declare a variable, and it's initialized to something crazy if I don't set it myself.

This option doesn't exist in MSVC, and honestly, whoever coded your application made a big mistake. That code is not portable, as C/C++ say that uninitialized variables have an undefined value. I suggest setting the "treat warnings as errors" option and recompiling; MSVC should give you a warning every time a variable is used without being initialized.

No - there's no option to do that in MSVC.
Debug builds will initialize them with something else (0xcc I think), but not zero. Unfortunately, your code is bugged and needs fixed (of course this applies only to automatic variables -for statics and globals it's fine to assume they're zero initialized). I'm surprised there was any compiler that supported that behavior - if there's an option to do that in GCC, I haven't heard of it (but I'm no expert in the dusty corners of GCC).
You may hear that an earlier version of MSVC would init variables to zero in debug builds (similar to the way 0xcc is used in VS 2005), but as far as I know that's untrue.
edit ----------
Well, I'll be damned - GCC does (or did?) have the -finit-local-zero option. Looks like it's there mostly for Fortran support, I think.
I'd suggest using compiler warnings about using uninitialized variables to help you catch 99% of your problems. I know it's not a great bit of work, but it should be done if at all possible.

Interestingly, MSVC now does have the ability to do this. The Microsoft Security team wrote a blog post about it here, and there's a CppCon talk here.
Unfortunately, it doesn't seem like this option is exposed to the public. This page lists a bunch of 'hidden MSVC flags', and it includes an option called -initall, so that might be it.

What I ended-up doing was switching to /w4. At this level, it caught most of the "yeah, that's going to be an issue" areas of initialization. Otherwise, there's nothing that can change everything from being 0xcccccccc on initialization to 0x00000000 that I saw.
Massive thanks to everyone for answering this, and yes, we will tighten it up in the future.

Related

Has anyone gotten lldb expression evaluation to work with C++11 on Mavericks?

I've been trying for weeks now to get lldb working with C++11 on Mavericks, and I just cannot get it working reliably. Has anyone managed this? What exact steps did you take?
Symptoms I find include:
(1) Unable to invoke basic std functions, like if I have a vector v in the code, I cannot call "v.size()" (earlier StackOverflow responses agreed with this).
(2) Generally gets confused all the time about data types and classes. Sometimes it understands simple things, sometimes it just gives odd error messages, and misinterprets user types.
(3) If I stop the code and call a bunch of other functions, lldb sometimes just gets very confused, and I have seen utterly bizarre run-time behavior (e.g., I call a function from lldb and get logically impossible results, as if the call stack or memory was somehow mangled).
(4) Sometimes lldb just gives up and seems to lose track of where it is on the stack.
I know these are vague, but has anyone used lldb extensively for expression evaluation (not just breakpoints, but calling functions and methods from with debugger) and had lldb work? I have these very complex, very large datastructures and need an interactive debugger to manipulate them, and invoke methods on them, interactively (i.e., a repl).
Not part of the question, but if anyone knows of a true C++11 debugger that can call methods and evaluate functions at run time interactively, and works reliably on MacOS Mavericks, I'd be very grateful.
N.B. earlier MacOS versions are entirely different from Mavericks.
I don't know about 2-4, they are not specific enough to really tell. But #1 turns out to be a problem with the new C++ standard library on OS X. It is pretty aggressive about inlining most of the std::* functions, and not creating out of line copies. That's actually usually exactly what you want, but it is inconvenient for debugging!
You usually see errors like:
(lldb) expr my_vec.size()
error: call to a function 'std::__1::vector<int, std::__1::allocator<int> >::size() const' ('_ZNKSt3__16vectorIiNS_9allocatorIiEEE4sizeEv') that is not present in the target
And that's because there is no function to call, there's only inlined versions sprinkled through-out your code.
In C++11 you can work around this if you know in advance you will want to call functions in some particular template class by putting:
template class std::vector<int>;
for instance, in you code somewhere. Probably want to do this inside some kind of #ifdef DEBUG construct, you wouldn't want to ship code this way.

Boost pretty print for GCC error messages

I'm using GCC 4.7.2. My code is rather heavy on template, STL and boost usage. When I compile and there is an error in some class or function that is derived from or uses some boost/STL functionality, I get error messages showing spectacularly hideous return types and/or function arguments for my classes/function.
My question:
Is there a prettyprint type of thing for GCC warnings/errors containing boost/STL types, so that the return types shown in error messages correspond to what I've typed in the code, or at least, become more intelligible?
I have briefly skimmed through this question, however, that is about GDB rather than GCC...
I've also come across this pretty printer in Haskell, but that just seems to add structure, not take away (mostly) unneeded detail...
Any other suggestions?
I asked a similar question, where someone suggested I try gccfilter. It's a Perl script that re-formats the output of g++ and colorizes it, shortens it, hides full pathnames, and lots more.
Actually, that suggestion answers this question really well too: it's capable of hiding unneeded detail and pretty-printing both STL and boost types. So: I'll leave this here as an answer too.
The only drawback I could see is that g++ needs to be called from within the script (i.e., piping to it is not possible at the time). I suspect that's easily fixed, and in any case, it's a relatively minor issue.
You could try STLfilt as mentioned in 'C++ Template Metaprogramming' by David Abrahms & Alesky Gurtovoy.
The book contains a chapter on template message diagnostics. It suggests using the STLFilt /showback:N to eliminate compiler backtrace material in order to get simplified output.

Go language warnings and errors

It seems that GO language does not have warnings in it. I've observed
few instances.
1. "declared and not used"(if variable is declared and not used
anywhere it gives an error and does not compile the program)
2. "imported and not used"(similarly if package is imported and not
used anywhere it gives an error and does not compile the program)
Can somebody help. If they have any pointers.
Go is trying to prevent this situation:
The boy is smoking and leaving smoke rings into the air. The girl gets
irritated with the smoke and says to her lover: "Can't you see the
warning written on the cigarettes packet, smoking is injurious to
health!"
The boy replies back: "Darling, I am a programmer. We don't worry
about warnings, we only worry about errors."
Basically, Go just wont let you get away with unused variables and unused imports and other stuff that is normally a warning on other languages. It helps put you in a good habit.
The Go Programming Language
FAQ
Can I stop these complaints about my unused variable/import?
The presence of an unused variable may indicate a bug, while unused
imports just slow down compilation. Accumulate enough unused imports
in your code tree and things can get very slow. For these reasons, Go
allows neither.
When developing code, it's common to create these situations
temporarily and it can be annoying to have to edit them out before the
program will compile.
Some have asked for a compiler option to turn those checks off or at
least reduce them to warnings. Such an option has not been added,
though, because compiler options should not affect the semantics of
the language and because the Go compiler does not report warnings,
only errors that prevent compilation.
There are two reasons for having no warnings. First, if it's worth
complaining about, it's worth fixing in the code. (And if it's not
worth fixing, it's not worth mentioning.) Second, having the compiler
generate warnings encourages the implementation to warn about weak
cases that can make compilation noisy, masking real errors that should
be fixed.
It's easy to address the situation, though. Use the blank identifier
to let unused things persist while you're developing.
import "unused"
// This declaration marks the import as used by referencing an
// item from the package.
var _ = unused.Item // TODO: Delete before committing!
func main() {
debugData := debug.Profile()
_ = debugData // Used only during debugging.
....
}
One solution for unused imports is to use goimports, which is a fork of gofmt. It automatically adds missing imports and removes unused ones (in addition to formatting your code).
http://godoc.org/code.google.com/p/go.tools/cmd/goimports
I've configured my editor to automatically run goimports whenever I save my code. I can't imagine writing go code without it now.
From what I just read, (wikipedia)
"Go's syntax includes changes from C aimed at keeping code concise and readable."
The word "concise" is very important to the compiler. I have found out
that the syntax enforced by the compiler is no longer "\n" or whitespace
agnostic. And there are no "warning" type errors.
There are good things about Go. There are some not so good things. The
attitude of no warnings is a bit extreme, especially when developing or testing
a new package. It seems that partial development is not acceptable. Warnings are not acceptable. It is either the production version or the highway. This is a very dualistic point of view. I wonder if evolution would have resulted in "life", if that had been the constraints on nature.
I can only hope that things will change. Death seems to be very beneficial at times.
I have tried Go, and I am disappointed. At my age I don't think I will return.

GCC hidden/little-known features

This is my attempt to start a collection of GCC special features which usually do not encounter. this comes after #jlebedev in the another question mentioned "Effective C++" option for g++,
-Weffc++
This option warns about C++ code which breaks some of the programming guidelines given in the books "Effective C++" and "More Effective C++" by Scott Meyers. For example, a warning will be given if a class which uses dynamically allocated memory does not define a copy constructor and an assignment operator. Note that the standard library header files do not follow these guidelines, so you may wish to use this option as an occasional test for possible problems in your own code rather than compiling with it all the time.
What other cool features are there?
From time to time I go through the current GCC/G++ command line parameter documentation and update my compiler script to be even more paranoid about any kind of coding error. Here it is if you are interested.
Unfortunately I didn't document them so I forgot most, but -pedantic, -Wall, -Wextra, -Weffc++, -Wshadow, -Wnon-virtual-dtor, -Wold-style-cast, -Woverloaded-virtual, and a few others are always useful, warning me of potentially dangerous situations. I like this aspect of customizability, it forces me to write clean, correct code. It served me well.
However they are not without headaches, especially -Weffc++. Just a few examples:
It requires me to provide a custom copy constructor and assignment operator if there are pointer members in my class, which are useless since I use garbage collection. So I need to declare empty private versions of them.
My NonInstantiable class (which prevents instantiation of any subclass) had to implement a dummy private friend class so G++ didn't whine about "only private constructors and no friends"
My Final<T> class (which prevents subclassing of T if T derived from it virtually) had to wrap T in a private wrapper class to declare it as friend, since the standard flat out forbids befriending a template parameter.
G++ recognizes functions that never return a return value, and throw an exception instead, and whines about them not being declared with the noreturn attribute. Hiding behind always true instructions didn't work, G++ was too clever and recognized them. Took me a while to come up with declaring a variable volatile and comparing it against its value to be able to throw that exception unmolested.
Floating point comparison warnings. Oh god. I have to work around them by writing x <= y and x >= y instead of x == y where it is acceptable.
Shadowing virtuals. Okay, this is clearly useful to prevent stupid shadowing/overloading problems in subclasses but still annoying.
No previous declaration for functions. Kinda lost its importance as soon as I started copypasting the function declaration right above it.
It might sound a bit masochist, but as a whole, these are very cool features that increased my understanding of C++ and general programming.
What other cool features G++ has? Well, it's free, open, it's one of the most widely used and modern compilers, consistently outperforms its competitors, can eat almost anything people throw at it, available on virtually every platform, customizable to hell, continuously improved, has a wide community - what's not to like?
A function that returns a value (for example an int) will return a random value if a code path is followed that ends the function without a 'return value' statement. Not paying attention to this can result in exceptions and out of range memory writes or reads.
For example if a function is used to obtain the index into an array, and the faulty code path is used (the one that doesn't end with a return 'value' statement) then a random value will be returned which might be too big as an index into the array, resulting in all sorts of headaches as you wrongly mess up the stack or heap.

Expressions which always return true (and the compiler doesn't know)

When experimenting I often use if (true) {..} or if (false) {..} to section off chunks of code I'm playing with.
The problem is that compilers these days sometimes issue a warning about unreachable code. I then have to promote my code to something like if ((10 % 2) == 0), but then some smarter compilers catch this as unreachable too.. (And so a small arms race begins..)
How do I solve this problem?
Try moving it out of the code, using pre-processor flags:
#if false
.... code which won't get run ....
#endif
Some IDEs will even collapse such un-runnable blocks for you to keep them out of the way.
Why not just use some kind of "environment variable" to control this kind of thing? Make it a reall conditional then you're not fighting the compiler.
if ( environment.MODE_EXPERIMENT) {
experimental code here
}
Personally I try pretty hard to avoid doing this kind of thing, we have SCM systems that allow us to keep old versions of code, really shouldn't need to do this too much.
This should do:
if (atoi("1")) {
}
This can also be useful to generate any kind of constant.
Almost every single language has a version of if(false) { } that a compiler/IDE won't complain about. The most common (afaik) look like the following:
/*
int i = 0;
String s = "I will never be run!";
*/
Yes, comments. Multi-line comments, to be exact. Stopping blocks of code from being run are pretty much their second main purpose (after documentation). if(true), of course, is then handled by not using them.
You're trying to re-invent the wheel here, and I have no idea why.

Resources