I have a class with the only constructor like this:
IntroScreen::IntroScreen(Game *game) :
View(game), counter(0.0f), message(-1), continueAlpha(255),
continueVisible(false), screenAlpha(255), fadeIn(false), fadeOut(false)
{
}
And somewhere in a method I have this if-statement
if (counter > 10.0f)
And Valgrind says for that line:
Conditional jump or move depends on uninitialised value(s)
But I initialized it in my initializer list! And I think I believe Valgrind. Because, sometimes everything goes correct and sometimes nothing happens.... So, maybe counter gets a wrong value and so it takes long until the counter reaches 10.
I already check my code where I use counter for some errors. But I think you can't "un-initialize a value" with a C++ statement...
These are ALL the lines (except in the initializer list) where I use counter:
counter += speed;
counter = 20.0f;
counter += game->getSpeedFactor();
if (counter >= 15.f)
counter = 15.f;
if (counter > 10.0f)
Valgrind gives the same output for screenAlpha.
Both variables are private and I have no friend classes....
So, what is going on? What the problem could be?
Edit:
I printed the value out:
In the constructor, it was correnct: 0
In my method, it was rubbish. It prited random values like:
-97298.8...
-106542.2...
The print statement is the first line of the method where all assignments to counter are in.
Second Edit:
Can this be the problem!!??
In my Game class, I initialize that IntroScreen like this:
Game::Game() : /* Some other stuff .... */ , view(new IntroScreen(this))`
{}
view is here a pointer to an abstract super-type of IntroScreen called View.
Did you accidentally shadow counter with a local variable that's uninitialized?
Otherwise, it's possible that valgrind is mid-diagnosing this in an object that was already deleted (using sentry values perhaps).
Or valgrind could just be wrong.
Not enough code to reproduce problem.
Generic SO / developer forum advice:
Do provide a minimal code snippet reproducing the problem.
Quite often (about 85% of all cases in my experience) the process of reducing the code snippet already uncovers the bug for you.
Edit: Your addition still doesn't give a compilable example of your problem, but enough information at least to identify then problem - or, at least, one of them:
Game::Game() : /* Some other stuff .... */ , view(new IntroScreen(this))`
{}
I am not sure whether a new() call is even legal in an initializer list. But I am sure that you do not have a fully initialized this at this point, so chances are your IntroScreen constructor does bogus things.
I found it:
getSpeedFactor() returns only the first time I call it a complete wrong number because of time-functions like gettimeofday(). The start value (to time how long it took to update the game) is set initialized to zero and the stop value is micros of the day: which gives a time of the whole day instead of the update time. Once the game loop ran once, the wrong value is corrected (because of the start value gets assigned). But the first time the game-logic was executed, I used getSpeedFactor() to assign counter, so that way counter get a value of -10000...
Thanks all.
Off the top of my head, you may need to define private default and copy constructors that have proper initializers. Haven't used valgrind, but it's a common thing to forget to do.
Just add a debugging printf statement or equivalent, if you have doubts. But I would not believe Valgrind this time.
BTW: delete does not "un-initliase" a value. It deletes object, but the pointer still points to that memory location — it does have a value.
Related
I am looking at a C++ class which has the following lines:
while( x > y );
return x - y;
x and y are member variables of type volatile int. I do not understand this construct.
I found the code stub here: https://gist.github.com/r-lyeh/cc50bbed16759a99a226. I guess it is not guaranteed to be correct or even work.
Since x and y have been declared as volatile, the programmer expects that they will be changed from outside the program.
In that case, your code will remain in the loop
while(x>y);
and will return the value x-y after the values are changed from outside such that x <= y. The exact reason why this is written can be guessed after you tell us more about your code and where you saw it. The while loop in this case is a waiting technique for some other event to occur.
It seems
while( x > y );
is a spinning loop. It won't stop until x <= y. As x and y are volatile, they may be changed outside of this routine. So, once x <= y becomes true, x - y will be returned. This technique is used to wait for some event.
Update
According to the gist you added, it seems the idea was to implement thread-safe lock-free circular buffer. Yes, the implementation is incorrect. For example, the original code-snippet is
unsigned count() const {
while( tail > head );
return head - tail;
}
Even if tail becomes less or equal to head, it is not guaranteed that head - tail returns positive number. The scheduler may switch execution to another thread immediately after the while loop, and that thread may change head value. Anyway, there are a lot of other issues related to how reading and writing to shared memory work (memory reordering etc.), so just ignore this code.
Other replies have already pointed out in detail what the instruction does, but just to recap that, since y (or head in the linked example) is declared as volatile changes made to that variable from a different thread will cause the while loop to finish once the condition has been met.
However, even though the linked code example is very short, it's a near perfect example of how NOT to write code.
First of all the line
while( tail > head );
will waste enormous amounts of CPU cycles, pretty much locking up one core until the condition has been met.
The code gets even better as we go along.
buffer[head++ % N] = item;
Thanks to JAB for pointing out i mistook post- with pre-increment here. Corrected the implications.
Since there are no locks or mutexes we obviously will have to assume the worst. The thread will switch after assigning the value in item and before head++ executes. Murphy will then call the function containing this statement again, assigning the value of item at the same head position.
After that head increments. Now we switch back to the first thread and increment head again. So instead of
buffer[original_value_of_head+1] = item_from_thread1;
buffer[original_value_of_head+2] = item_from_thread2;
we end up with
buffer[original_value_of_head+1] = item_from_thread2;
buffer[original_value_of_head+2] = whatever_was_there_previously;
You might get away with sloppy coding like this on the client side with few threads, but on the server side this could only be considered a ticking time bomb. Please use synchronisation constructs such as locks or mutexes instead.
And well, just for the sake of completeness, the line
while( tail > head );
in the method pop_back() should be
while( tail >= head );
unless you want to be able to pop one more element than you actually pushed in (or even pop one element before pushing anything in).
Sorry for writing what basically boils down to a long rant, but if this keeps just one person from copying and pasting that obscene code it was worth while.
Update: Thought i might as well give an example where a code like while(x>y); actually makes perfect sense.
Actually you used to see code like that fairly often in the "good old" days. cough DOS.
Was´nt used in the context of threading though. Mainly as a fallback in case registering an interrupt hook was not possible (you kids might translate that as "not possible to register an event handler").
startAsynchronousDeviceOperation(..);
That might be pretty much anything, e.g. tell the hardisk to read data via DMA, or tell the soundcard to record via DMA, possibly even invoke functions on a different processor (like the GPU). Typically initiated via something like outb(2).
while(byteswritten==0); // or while (status!=DONE);
If the only communication channel with a device is shared memory, then so be it. Wouldnt expect to see code like that nowadays outside of device drivers and microcontrollers though. Obviously assumes the specs state that memory location is the last one written to.
The volatile keyword is designed to prevent certain optimisations. In this case, without the keyword, the compiler could unroll your while loop into a concrete sequence of instructions which will obviously break in reality since the values could be modified externally.
Imagine the following:
int i = 2;
while (i-- > 0) printf("%d", i);
Most compilers will look at this and simply generate two calls to printf - adding the volatile keyword will result in it instead generating the CPU instructions that invoke a counter set to 2 and a check on the value after every iteration.
For example,
volatile int i = 2;
this_function_runs_on_another_process_and_modifies_the_value(&i);
while(i-- > 0) printf("%d", i);
Is it better to declare and initialize the variable or just declare it?
What's the best and the most efficient way?
For example, I have this code:
#include <stdio.h>
int main()
{
int number = 0;
printf("Enter with a number: ");
scanf("%d", &number);
if(number < 0)
number= -number;
printf("The modulo is: %d\n", number);
return 0;
}
If I don't initialize number, the code works fine, but I want to know, is it faster, better, more efficient? Is it good to initialize the variable?
scanf can fail, in which case nothing is written to number. So if you want your code to be correct you need to initialize it (or check the return value of scanf).
The speed of incorrect code is usually irrelevant, but for you example code if there is a difference in speed at all then I doubt you would ever be able to measure it. Setting an int to 0 is much faster than I/O.
Don't attribute speed to language; That attribute belongs to implementations of language. There are fast implementations and slow implementations. There are optimisations assosciated with fast implementations; A compiler that produces well-optimised machine code would optimise the initialisation away if it can deduce that it doesn't need the initialisation.
In this case, it actually does need the initialisation. Consider if scanf were to fail. When scanf fails, it's return value reflects this failure. It'll either return:
A value less than zero if there was a read error or EOF (which can be triggered in an implementation-defined way, typically CTRL+Z on Windows and CTRL+d on Linux),
A number less than the number of objects provided to scanf (since you've provided only one object, this failure return value would be 0) when a conversion failure occurs (for example, entering 'a' on stdin when you've told scanf to convert sequences of '0'..'9' into an integer),
The number of objects scanf managed to assign to. This is 1, in your case.
Since you aren't checking for any of these return values (particular #3), your compiler can't deduce that the initialisation is necessary and hence, can't optimise it away. When the variable is uninitialised, failure to check these return values results in undefined behaviour. A chicken might appear to be living, even when it is missing its head. It would be best to check the return value of scanf. That way, when your variable is uninitialised you can avoid using an uninitialised value, and when it isn't your compiler can optimise away the initialisations, presuming you handle erroneous return values by producing error messages rather than using the variable.
edit: On that topic of undefined behaviour, consider what happens in this code:
if(number < 0)
number= -number;
If number is -32768, and INT_MAX is 32767, then section 6.5, paragraph 5 of the C standard applies because -(-32768) isn't representable as an int.
Section 6.5, paragraph 5 says:
If an exceptional condition occurs during the evaluation of an
expression (that is, if the result is not mathematically defined or
not in the range of representable values for its type), the behavior
is undefined.
Suppose if you don't initialize a variable and your code is buggy.(e.g. you forgot to read number). Then uninitialized value of number is garbage and different run will output(or behave) different results.
But If you initialize all of your variables then it will produce constant result. An easy to trace error.
Yes, initialize steps will add extra steps in your code at low level. for example mov $0, 28(%esp) in your code at low level. But its one time task. doesn't kill your code efficiency.
So, always using initialization is a good practice!
With modern compilers, there isn't going to be any difference in efficiency. Coding style is the main consideration. In general, your code is more self-explanatory and less likely to have mistakes if you initialize all variables upon declaring them. In the case you gave, though, since the variable is effectively initialized by the scanf, I'd consider it better not to have a redundant initialization.
Before, you need to answer to this questions:
1) how many time is called this function? if you call 10.000.000 times, so, it's a good idea to have the best.
2) If I don't inizialize my variable, I'm sure that my code is safe and not throw any exception?
After, an int inizialization doesn't change so much in your code, but a string inizialization yes.
Be sure that you do all the controls, because if you have a not-inizialized variable your program is potentially buggy.
I can't tell you how many times I've seen simple errors because a programmer doesn't initialize a variable. Just two days ago there was another question on SO where the end result of the issue being faced was simply that the OP didn't initialize a variable and thus there were problems.
When you talk about "speed" and "efficiency" don't simply consider how much faster the code might compile or run (and in this case it's pretty much irrelevant anyway) but consider your debugging time when there's a simple mistake in the code do to the fact you didn't initialize a variable that very easily could have been.
Note also, my experience is when coding for larger corporations they will run your code through tools like coverity or klocwork which will ding you for uninitialized variables because they present a security risk.
This one is WTF city.
The below program is crashing after a few thousand loops.
unsigned long int nTurn = 1;
bool quit = false;
int main(){
while(!quit){
doTurn();
++nTurn;
}
}
That's, of course, simplified from my game, but nTurn is at the moment used nowhere but the incrementing of it, and when I comment out the ++nTurn line, the program will reliably loop forever. Shouldn't it run into the millions?
WTF, stackoverflow?
Your problem is elsewhere.
Some other part of the program is reading from a wild pointer that ends up pointing to nTurn, and when this loop changes the value the other code acts different. Or there's a race condition, and the increment makes this loop take just a tiny bit longer so the race-y thing doesn't cause trouble. There are an infinite number of things you could have wrong elsewhere.
Can you run your program under valgrind? Some errors it won't find, but a lot it will.
may sound silly, but, if I were looking at this, I'd perhaps output the nTurn var and see if it were always crashing out on the value. then, perhaps initialize nTurn to that & see if that also causes it. you could always put this into debug and see what is happening with various registers and so forth. did you try different compilers ?
I'd use a debugger to catch the fault and see the value of nTurn. Or if you have core dump from the crash load it into the debugger to see the var values at the crash time.
One more point, could the problem be when nTurn wraps round and goes to zero?
++nTurn can't be the source of the crash directly. You may have some sort of buffer overflow causing the memory for the nTurn variable to be accessed by pointer arithmetic when it shouldn't be. That would cause weird behavior when combined with the incrementing.
I've been messing around in C++ a little bit but I'm still pretty new. I searched around a little bit and even using the keywords of exactly the problem I am trying to tackle yields no results. Basically I am just trying to figure out how to tell if a variable has no data. I have a file that my program reads and it searches for a specific character within that file and basically uses delimiters to determine where to store the actual data in a variable. Now I added some comments in the file saying that it should not be edited which has caused me some problems. So I pretty much want to count the number of comments, but I'm not sure how to do it because the way I had it set up was resulting in huge numbers being returned. So I figured I would attempt to fix it with a simple if statement to see if there was any data in the array while it was running the loop, and if there was then simply add +1 to my variable. Needless to say it did not work. Here's the code. And if you know a better way of doing this, by all means please do share.
size_t arySearchData[20];
size_t commentLines[20];
size_t foundDelimiter;
size_t foundComment;
int commentsNum;
foundDelimiter = lineText.find("]");
foundComment = lineText.find("#");
if (foundComment != std::string::npos) {
commentLines[20] = int(foundComment);
if (foundComment = <PROBLEM>){
commentsNum++;
}
}
So it successfully gets the two comments in my file and recognizes that they are located at the first index(0) in each line but when I tried to have it just do commentsNum++ in my first if statement it just comes up with tons of random numbers, and I am not sure why. So as I said my problem is within the second if statement, I need a void or just a better way to solve this. Any help would be greatly appreciated.
And yes I do realize I could just determine if there 'was' data in the there rather than being void or null but then it would have to be specific and if the comment (#) had a space before it, then it would render my method of reading the file useless as the index will have changed.
A variable in C++ always contains data, just it may not be initialised.
int i;
It will have some value, what it is can't be determined until you do something like
i = 1337;
until you do that the value of i will be what ever happened to be in the memory location that i has been assigned to.
The compile may pick up on the fact that you are trying to use a variable which you have not actually given a value your self, but this will normally just be a warning, as their is nothing wrong as such with doing so
You do not initialize commentsNum. Try this:
int commentsNum = 0;
In C++ other than static variables, other variables are assigned undetermined values. This is primarily done to adhere to underlying philosophy -- "you don't pay for things you don't use", so it doesn't zero that memory by default." However, for static variables, memory is allocated at link time. Unlike runtime initialization, which would need to happen in local variables, link time allocation and initialization incur low cost.
I would recommend hence setting int commentsNum = 0;
I have a few simple lines of code (below). [bp] indicates a breakpoint.
for(int i=0;i<300;i++){}
int i=0;
cout<<i;
[bp] for (i=0;i<200;i++){}
When I debug this in visual studio, it tells me that i is equal to 300 on the breakpoint. Annoyingly, 0 is printed to the console. Is there any way to make it realize that two variables in different scopes can actually have the same name?
I also want to add some code to the second loop and then debug it - but when I try to do that, i is consistently shown as 300. Very annoying.
in my visual studio, looking at the debugger Locals window
i 300 int
argc 1 int
argv 0x00214b88 wchar_t * *
i 0 int
NOTE! there are two i varibles in the debug output, i == 300 and i == 0
I'm thinking the reason its getting confused is a quirk/bug of the debugger where it tracks both i's then gets confused when you hover over an i, it just returns the first i? or some such, I don't think its semantically checking which i to show.
If your breakpoint is on the
for (i=0;i<200;i++){}
line, that means that the new i hasn't initialized yet when the breakpoint is hit, because that line of code hasn't executed yet. So it's still carrying the original i value.
Brace for impact
The use of the same varibale for different perpose at different places in code is NOT ideal.
Here's the solution though:
Use braces to separate the different use-cases of the same variable.
for(int i=0;i<300;i++){}
{
int i=0;
cout<<i;
}
{
[bp] for (i=0;i<200;i++){}
}
NOTE:
As Robert rightly pointed out, unless the instruction is executed,
i will not be initialised to the new value.
GoodLUCK!!
The third i can alias the first i, because they have non-overlapping scopes. The second i cannot alias the third, because their scopes do overlap.
Hence, the compiler knows it needs to allocate storage for at least two integers. The space for the first integer can be shared by the first and third i, and the the space for the second i is reserved exclusively for the second i. These locations could be registers or stack slots, without loss of generality.
Interim conclusion: for the compiler, it doesn't matter how often you use the name i. It only cares how many variables you have, and how their scopes overlap.
So, when the debugger hits the second for-loop, it sees that you're watching the third i. The debugger looks up the location of the third i. Since that location was also used for the first i, it still contains 300. That of course doesn't matter for the program, as you start out by writing 0 to the third i, overwriting the old value 300 in that location.
So, the essential step is understanding how variables can be mapped to locations.