C++ handles an uninitialized field in a strange way - c++

The sample below shows reading an uninitialized field a.i1 in two ways. The first call does not compile. However, calling a.donothing() that does not do anything, the original call compiles fine and prints the default value 0. Why is this inconsistency?
I am using Visual Studio Community 2015, the compiler output is as follows:
Severity Code Description Project File Line Suppression State
Error C4700 uninitialized local variable 'a' used
class A {
public:
int i1;
void donothing() {}
};
int main() {
A a;
cout << "main1: " << a.i1 << endl; // compile fails
a.donothing();
cout << "main2: " << a.i1 << endl; // prints 0 (default)
return 0;
}

Compiler is doing what it ought to do. You can fix it like this (as one solution out of many):
class A {
public:
A(int i = 0) : i1(i) {}
int i1;
void donothing() {}
};

In both cases a warning must be issued, at most. The fact that calling donothing cancels the error is a clear indication that this is a bug. You can report it at Microsoft Connect.
A simple workaround for this problem is to change the declaration to A a{};.
You can test your code on different compilers at Compiler Explorer.
[EDIT] The warning message C4700 is treated as an error if Security Development Lifecycle is turned on (/sdl).

Depends on the compiler, the compiler should supply a default constructor that will initialize your members with a default value. But this behavior is not dependable. Since C++11 you can say ClassName()=default; The best practice is to prove your own default constructor.
Your code never had any compiler errors with g++ 5.4.0
#include <iostream>
using namespace std;
class A {
public:
//A() : i1(0) { } // compiler will provide this if you don't write anything
// since C++ 11 you can also say A() = default;
A() = default;
int i1;
void donothing() {}
void writeMember() const { cout << "i1 value: " << i1 << endl; }
};
// better provide a signature for the main function
int main(int argc, char* argv[]) {
A a;
a.writeMember();
cout << "main1: " << a.i1 << endl; // compile fails
a.donothing();
cout << "main2: " << a.i1 << endl; // prints 0 (default)
return 0;
}
To compile the above code stored in testclass.cpp
g++ -std=c++11 -o testclass testclass.cpp
By using the C++11 default I got
i1 value: 4196976
main1: 4196976
main2: 4196976
If you comment out A()=default; this will rely on the compiler provided initializer, or the compiler may be lazy and not doing anything for performance reasons. You get
i1 value: 4196944
main1: 4196944
main2: 4196944
If you uncomment the line after public: you should consistently get 0
This illustrates the importance of adhering to good conventions of alway provide your own default constructor. The compiler maybe doing the right thing by not assigning any particular value to your member because you may assign another value in the next operation. This can save one operation. The member will be simply allocated on the stack, in that case the member got a random value. If you run this code on a different computer you will for sure get a different value.

Related

inline variable is initialized more than once

Im seeing some examples of inline const variable getting initialized (and destructed) 3 times with visual studio 2017. Is this is a bug with the linker ? or is this supposed to happend in some other way ?
linker Comdat folding is set to Off.
Example Code:
#pragma once
struct A {
A() {
static int count = 0;
++count;
ASSERT(count == 1);
}
~A() {
}
};
inline const A a = A();
In my solution, I have the assert fire twice (A constructor called 3 times).
Inspecting the call stack shows all call stacks are identical and all calls come from dynamic initializer for a(). Now I know for a fact this class is not used in other parts of the solution since I just created it to investigate this issue.
Im using VS17 15.8.9
Update: Bug report here https://developercommunity.visualstudio.com/content/problem/297876/static-inline-variable-gets-destroyed-multiple-tim.html (you may upvote to help push for the bugfix)
This appears to be an MSVC bug. I'm able to reproduce it with the code below (also with VS2017 15.8.9). Interestingly, I can only reproduce with a Debug build. In Release mode, the optimizer seems to save us.
Common.h
#pragma once
#include <iostream>
class Foo
{
public:
Foo()
{
std::cout << "Constructing a Foo" << std::endl;
}
~Foo()
{
std::cout << "Destructing a Foo" << std::endl;
}
};
inline Foo const Bar;
other.cpp
#include "common.h"
void DoOtherStuff()
{
std::cout << &Bar << std::endl;
}
main.cpp
#include "common.h"
void DoStuff()
{
std::cout << &Bar << std::endl;
}
extern void DoOtherStuff();
int main()
{
DoStuff();
DoOtherStuff();
}
Output (Debug)
Constructing a Foo
Constructing a Foo
00007FF74FD50170
00007FF74FD50170
Destructing a Foo
Destructing a Foo
I get the bug in both debug and release (/Ox) mode using the MS C++ compiler version 19.16 (comes with, e.g., Visual Studio 15.9.4).
Inline.Hpp
#include <iostream>
inline struct Foo
{ Foo() { std::cout << "Constructing a Foo at " << this << std::endl; } }
Instance;
Inline.cpp
#include "Inline.Hpp"
int main() { return 0; }
Inline2.cpp
#include "Inline.Hpp"
After compiling and linking inline.cpp and inline2.cpp, the output on running is:
Constructing a Foo at 00BE4028
Constructing a Foo at 00BE4028
The compiler and linker correctly resolve the two inline definitions to a single object, but incorrectly call the constructor for each definition, instead of just once. This is a serious bug which renders the "inline variable" feature of C++17 unusable. The "workaround" is to regard inline variables as still unsupported by MS C++ as of version 19.16, even when the /std:c++17 switch is used.
As of today there is an update for visual studio 2017 to version 15.9.24 which fixes the problem.
From the release notes:
Fixed C++ compiler bug for proper folding of inline variable dynamic
initializers.

C++ compiler not throwing error for undeclared variable

I tried to search for this specific problem and did not find anythying concrete.
I was using an undeclared variable in my program and the compiler did not complain, it just gave a warning and the program runs fine. My gcc version is 4.1.2
Below is a sample program I wrote to reproduce this, the variable "index" is not declared, why is the compiler treating "index" as a function and where does it find the definition of the function?
#include <iostream>
using namespace std;
int testfunction()
{
try {
cout << "inside testfunction method\n";
return 2;
} catch(...) {
cout << "caught exception" << index << endl;
}
return 1;
}
int main()
{
cout << "Testfunction return value : " << testfunction() << endl;
}
Compiling:
~ g++ throwreturntest.cpp
throwreturntest.cpp: In function ���int testfunction()���:
throwreturntest.cpp:11: warning: the address of ���char* index(const char*, int)���, will always evaluate as ���true���
Running :
~ ./a.out
inside testfunction method
Testfunction return value : 2
Looks like index is the name of a GCC builtin function:
http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
So it is already declared, just not by you.
The compiler is quite verbose about the situation. It things that index is an address of a function with signature
char *index(const char *s, int c);
See man index(3). The corresponding header is somewhere in the chain of <iostream>

Profiling C++ Destructor Calls

I am profiling a C++ application compiled on optimization level -O3 with the intel c++ compiler from intel composer xe 2013. The profiler (Instruments on OS X) states that a very large portion of time is being spent calling the destructor for a particular type of object. However, it will not provide me with information regarding what function allocated the object in the first place. Is there any tool that can provide the information on what functions allocate the largest quantity of a certain type of object?
Edit: I have also tried the -profile-functions flag for the intel c++ compiler with no success.
You could add two more parameters to the constructor, the file and the line number. Save that information in the object, and print it when the destructor is called. Optionally you could hide some of the ugliness in a macro for the constructor.
#include <iostream>
#include <string>
using std::string;
class Object
{
string _file;
int _line;
public:
Object( const char * file, int line ) : _file(file), _line(line) {}
~Object() { std::cerr << "dtor for object created in file: " << _file << " line: " << _line << std::endl; }
};
int main( int argc, char * argv[] )
{
Object obj( __FILE__, __LINE__ );
return 0;
}
This is how it runs
$ g++ main.cpp -o main && ./main
dtor for object created in file: main.cpp line: 16
$

C++ callback function run time error

I have a function that accepts function pointer as an argument and calls the function pointer as shown below.
int foo (int a, int(*calc)(int))
{
int y;
// ....
// calling calc function via callback
(*calc)(y);
}
The calc function to be called back looks like
int calc(int x)
{
// ....
cout << x;
checkValue(x);
}
function foo is placed in a.cpp and function calc() and checkValue() are defined in files b.cpp and c.cpp. My problem is calc() executes fine until the cout statement and fails to call checkValue() function. The crash report I received is:
symbol lookup error:..... undefined symbol: _ZNSaIcEC1Ev, version GLIBCXX_3.4
How can I solve this problem?
The symbol _ZNSaIcEC1Ev is the mangled name for the std::allocator<char>::allocator() zero-argument constructor (I determined this using the c++filt(1) program). The error message "symbol lookup error:..... undefined symbol" relates to dynamic linking and has nothing to do with calling a function through a function pointer.
Your error almost certainly lies somewhere else. You're probably getting confused about the location of the error due to stdout buffering -- strings are getting printed to stdout, but you're not seeing them show up because they're getting buffered in memory, and then the program crashes before they're displayed. To avoid that, you need to make sure to flush the output after every print statement (e.g. by inserting std::cout << std::endl or std::cout << std::flush or explicitly calling std::cout.flush()), or by using std::cerr instead of std::cout, which is unbuffered by default.
#include <iostream>
using namespace std;
int calc(int x){
cout<< "calc:" << x << endl;
}
int CALC(int x) {
cout << "CALC: " << x << endl;
}
int foo (int a, int(*callback)(int)){
cout << "Calling calc on:" << a << endl;
(*callback)(a);
}
int main() {
cout << "START" << endl;
foo(5, calc);
foo(6, CALC);
}
This works fine for me.
gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00)
Note: I removed your "checkValue(x)" call, the issue could be in there...

How do I imitate the Microsoft version of __FUNCTION__ using gcc?

When I use the __FUNCTION__ macro/variable to print out debugging information, there seems to be a difference in what it outputs when using the Microsoft C++ compiler and gcc. For example, using the following trivial code:
class Foo
{
public:
void Bar(int a, int b, int c)
{
printf ("__FUNCTION__ = %s\n", __FUNCTION__);
}
};
int main (void)
{
Foo MyFoo;
MyFoo.Bar();
return 0;
}
Using the Microsoft Visual C++ compiler, I get
__FUNCTION__ = Foo::Bar
whereas when compiling using gcc (in this case on the Mac), I get
__FUNCTION__ = Bar
The second example is not ideal because I quite often have several classes with, say, Init() and Uninit() methods and in a debug output trace its virtually impossible to tell which one of these has been called as the class name will be missing. Now, I know you can use the __PRETTY_FUNCTION__ in place of __FUNCTION__ to get something like
__PRETTY_FUNCTION__ = void Foo::Bar(int, int, int)
Which is fine, but its a bit too verbose for what I need and gets a bit long for functions with a lot of parameters.
So my question is (at last), is there any way to get the output to look like simply Foo::Bar using gcc, as in the example above?
If you are using it for tracing, you can always use typeid(T).name() and just conditionally compile per platform. Certainly not as convenient as the macro, but it could work.
Vaguely similar to __CLASS__ macro in C++
The function-name sanctioned by the standard is defined as follows:
static const char __func__[] = "function-name ";
Example:
#include <iostream>
namespace meh {
void foobar() { std::cout << __func__ << std::endl; }
};
struct Frob {
void foobar() { std::cout << __func__ << std::endl; }
static void barfoo() { std::cout << __func__ << std::endl; }
};
int main () {
std::cout << __func__ << std::endl;
meh::foobar();
Frob().foobar();
Frob::barfoo();
}
However, output with g++:
main
foobar
foobar
barfoo
However, that is valid C++ behaviour:
§ 8.4.1, 8: The function-local predefined variable __func__ is defined as if a definition of the form static const char __func__[] = "function-name ";
had been provided, where function-name is an implementation-defined string. It is unspecified whether such a variable has an address distinct from that of any other object in the program
I.e., you may not trust in its value. If you want to use non-portable extensions, have a look at a similar question: What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__? .