Strange GCC optimisation bug [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I'm writing a fairly large application containing many different modules. I've always been programming with the GCC debugging info turned on and all optimisations turned off, for obvious reasons of debugging. Now I've decided that it's time for a release and I've set GCC to optimise to the best of it's abilities (-O3). And this is when the strangest of bugs appeared. Take the following code:
void SomeClass::setValue(int i) { this->iValue = i; }
int SomeClass::getValue() const { return this->iValue; }
Now without optimisations, these work perfectly. With optimisations, the value of SomeClass.iValue is not modified in the setValue() method. In fact, the output of the following:
cout << x.getValue();
x.setValue(5);
cout << x.getValue();
returns
0
0
when the iValue is intialised in the class to 0.
Now the strange part: if I insert the following code into setValue():
void SomeClass::setValue(int i) { cout << "Narf"; this->iValue = i; }
the code works!
Can someone please explain to me what is going on?

did you try checking cout<<x.iValue; ? perhaps the problem is in SomeClass::getValue(); for example, it returning void or being const ? :)
also, just an idea, the optimisation might happen in cout not your actual code as hinted by cout << "Narf";

Firstly, your code is not exactly correct. Getter function should return int instead of void. I think you just typed it incorrectly here, because gcc will not let you compile that (std::cout has no overloaded operator << for type void). What is more, SomeClass.i_value doesn't compile either. Did you mean this->i_value or just i_value?

Related

Using #define the wrong way round works for calling functions. Why? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
C and C++ documentation for the use of #define suggests that this should not work as I am using the define to replace the text MyFunc() with _myfunc(), which is a function that does not exist:
#define MyFunc _myfunc
void MyFunc()
{
cout << "This Prints!" << endl;
}
int Main()
{
_myfunc();
return 0;
}
My guess is that the compiler is being clever. It knows that _myfunc() does not exists and therefore does not replace the text and simple uses MyFunc().
I can't find any documentation to support this theory. Does anyone know whether this is correct?
After the preprocessor has run, your program will look like:
void _myfunc()
{
cout << "This Prints!" << endl;
}
int Main()
{
_myfunc(); // #1
return 0;
}
Ignoring other errors here (lack of includes, ...), the compiler can find _myfunc declared and defined, so naturally it will be found by overload resolution at the call site #1.

Why does the Sleep() function behave like this? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm playing around with the Sleep() function in C++ right now, and I am not understanding why this code operates the way it does.
I made a program to find the difference between two times, but it is not working as expected.
#include <iostream>
#include <chrono>
#include <Windows.h>
using namespace std;
int main() {
int timeA = (int)chrono::system_clock::now;
cout << timeA << "\n";
for (int i = 0; i < 5; i++) Sleep(1000);
int timeB = (int)chrono::system_clock::now;
cout << timeB << "\n";
int timeDifference = timeB - timeA;
cout << timeDifference;
cin.get();
return 0;
}
It seems as if the program is setting the variables at the same time, and then sleeping. Is this the case? If so, help me to understand why, please.
now is a function, not an attribute or variable. You failed to call it, and are casting the function pointer itself to int, which will always produce the same value for a given run (on a typical 64 bit system, the low 32 bits of the address where now is located).
Change both lines to use chrono::system_clock::now(), not chrono::system_clock::now.
Note that this is one of the reasons to avoid C-style casts, as well as a reason to compile with warnings turned up; it protects you from casting to wildly incorrect end results, without at least some sort of alert.

C++ beginner got 42 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Getting Douglas Adams vibes here...
I just started out with c++ and doing some code challenges right now.
The current challenge is to create a function that takes a number as its only argument and returns true if it's less than or equal to zero, otherwise return false.
However, when I run the program I get the number 42??
I actually don't need help for the challenge itself, I just wonder if someone could explain why I get this result :)
#include <iostream>
#include <string>
using namespace std;
bool lessThanOrEqualToZero(int num)
{
if (num <= 0) {
return true;
}
}
int main()
{
cout << lessThanOrEqualToZero(5);
}
The function bool lessThanOrEqualToZero(int);, as defined, makes your program have undefined behavior since not all paths in the function leads to the function returning a bool that you declared that it should return. Specifically: If num > 0 is true the function doesn't return a value.
When a program has undefined behavior, you can't trust anything it does. Your program could therefore print just about anything or nothing, crash or do something completely wild.
In some compilator implementations, a value could be picked from the stack where it expects to find the promised bool and then print whatever that value was (42 in your case). The stack will then be corrupt. Other implementations may compile it into a program that does something completely different. You'll never know.
The solution is to make sure that all paths leads to a return:
bool lessThanOrEqualToZero(int num)
{
if (num <= 0) {
return true;
}
return false;
}
This however better written as:
bool lessThanOrEqualToZero(int num)
{
return num <= 0;
}
otherwise return false
Well then you do need to return false otherwise.

What does struct object represents? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
#include<iostream>
using namespace std;
struct A{
int a;
int s;
};
int main()
{
A *S =new A();
A obj1=S[0];
printf(" 0x%x",obj1);
}
My question is when i see the out put it seems be 0x0;
and is some cases it becomes 0xFFFFFFFF
can someone explain?
Your program has undefined behavior, so is wrong (because what you pass to printf does not match the " 0x%x" format control string, since it has the wrong type); see also this answer.
Read Lattner's blog on undefined behavior (it also applies to C++)
Notice that printf is a C library function (so you need to #include <cstdio>). In genuine C++11, you would use some operator << on std::ostream-s, probably like
std::cout << obj1 << std::endl;
and that line won't compile (unless you define such an operator, which you should do).
To explain the actual behavior (which is non reproducible in general), you need to dive into implementation details (and you don't want to: if you did, study the source and object code of your particular program and C++ library, of your compiler, of your operating system, look into calling conventions, instruction set, ABIs, etc...). The displayed garbage value (e.g. 0xfffffff) is what happens to sit in some relevant processor register or memory location (on the call stack).
BTW, if you compiled with all warnings & debug info (e.g. g++ -Wall -Wextra -g with GCC) you'll get a warning. I strongly recommend to enable all warnings.
Notice that a struct A{ is the same as class A{public: so you could define some explicit constructor (which would initialize the fields) and some output operator<<:
struct A{
int a;
int s;
A(int aa=0, int ss=0) : a(aa), s(ss) {};
};
std::ostream operator << (std::ostream&out, A a) {
out << "a=" << a << ",s=" << s;
return out;
}
But you probably should read about the rule of five notably this.

array of pointers in C++ and what is "BUS ERROR" [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
#include<cstdio>
#include<string>
#include<iostream>
using namespace std;
int main()
{
int a[]={0,1,2,3};
int *r[]={NULL};
for(int i=0;i<4;i++)
{
r[i]=&a[i];
cout << &a[i] << endl;
cout << a[i]<<endl;
}
for(int i=0;i<4;i++)
{
cout << r[i] << endl;
cout << *r[i] << endl;
}
return 0;
}
I have started working on the array of pointers very recently. Can someone please help me out in finding the mistake in the above program..
I attached the screenshots of the results when run on windows and linux platforms.
On Windows,the addresses of the *r[] and a[] are matching and still the values are not matching.
On linux,it says "BUS ERROR" sometimes and "Segmentation fault" sometimes.
It would be better if someone explain what the "BUS ERROR" mean? And why does it come for this program.
Your array r only has space for a single element in it, but you store 4. That overwrites memory, causing the crash.
Change this:
int *r[]={NULL};
to:
int *r[sizeof a / sizeof *a];
This makes r have the same number of elements as a, in other words 4.
int *r[]={NULL}; should be int *r[]={0, 0, 0, 0};
That will allocates space for four pointers that your following code need.
BUS ERROR: What is a bus error?
Your are not allocating enough space for your r. Try int *r[4]; and you will not get a segmentation fault.
int *r[] = {0} it's equivalent with int *r[1];
r is an array of pointers, but in your code, it has only one element. You are lucky to run it on windows but it's a undefined behavior. It might seem to work today, on your compiler, but it is not legal C or C++, and there is no guarantee that it'll still work the next time you run the program. Or that it hasn't overwritten essential data even now, and you just haven't encountered the problems that is going to cause yet.