Debugging C++ queues in an IDE - c++

I want to debug this code segment:
#include <iostream>
#include <queue>
#include <random>
#include <time.h>
using namespace std;
int main()
{
cout << "Hello, World!" << endl;
queue<int> q;
srand(time(NULL));
for(int i = 0; i < 10; i++)
{
q.push(rand() % 100);
}
int a = q.front();
q.pop();
int b = q.front();
q.pop();
cout << "a: " << a << ", b: " << b << endl;
return 0;
}
I tried to debug it on 2 IDEs - CLion (my personal favorite) and VS2015. However, both of those did not show the queue items (as they would if I'd use an array, for instance):
CLion
VS2015
As I continued investigating, I noticed that if I remove the upper breakpoint in CLion, it does show the queue elements:
CLion - good version
Any ideas about why does it happen, and if there's a way to see the queue elements in the "bad" cases?

Removing the upper break point and switching between 32 and 64 bit compilations won't affect this. The 32/64 bits have to do with the generated assembly code. Once the code compiles correctly, the 32 and 64 bit assembly codes won't be the same but the program itself will still retain equivalent functionality. That is, 64 bit programs can't "do more" than 32 big programs. This is an ultra watered-down definition of Turing-completeness, but the upshot here is that it doesn't matter for the purposes of what you're trying to do right now whether you set your build target to 32 or 64 bits.
The IDE that you use will have a minimal effect here though, because they use different Debuggers. Since both debuggers did the same thing in your case, I'd say we can safely chalk it up to user error (see below), but like I said in my afterword, if you will, keep working with the debugger. It's an absolutely essential skill to master. Props to you for getting started early.
As for your debug problem, here is my debug of your program. Notice the breakpoints I used. Like Jesus Christ said before me, the debug worked correctly for both of us. The usual suspect in these cases is trying to debug the release build. When you compile a debug build, the compiler does not perform as many optimizations to allow you to trace your code through the variables and see exactly what's going on. Once your code functions correctly, you can switch to the release version and your compiler will optimize away a lot of the variables for maximum performance.
If you did debug under the Debug build as you said, then I'd say just chalk it up to debugger error. If you're a C++ newbie, there's a chance you just might not be experienced enough to navigate the intricacies of the debugger. No disrespect intended, but debugging is just as much an art as it is a science, and a new developer would not be faulted for not knowing how exactly to maneuver the tool.

I found a solution for the CLion problem - simply press on the variable in the variables tab, then press on Duplicate Watch (marked in red circle bellow, hotkey: ctrl+D) and you're done:

Did you compile with debug selected in the project?
I can clearly see queue values.

Make sure that
1) you are debugging Debug build (that is debug information is present and no optimization is done)
Project Properties -> C/C++ -> General -> Debug information format is set to "Program Database"
Project Properties -> Linker -> Generate Debug info is set to "/DEBUG")
2) raw structure mode is disabled
Tools -> Options -> Debugging -> Show raw structure of objects is not checked

Related

How do i get "winver"?

I'm trying to get the version number presented in cmd command "winver", which in my case is 20H2. How do i get that with code? I have found no posts covering this topic.
IMHO you maintain a map of build numbers and their strings, like
#include <iostream>
#include <map>
int main() {
std::map<int,std::string> builds = {{19042, "20H2"}, {19043, "21H1"}};
std::cout << builds.at(19042) << std::endl;
return 0;
}
and you would get the build number with GetVersion() or GetVersionEx(). See Wikipedia for a list. Note that the build number may be subject to compatibility settings, i.e. Windows may be lying to you.
IMHO Microsoft recommended to check the version of a system DLL like kernel32.dll with GetFileVersionInfo() to get the real version.
If you don't like any of these, getting the name from the Registry may be the option you're looking for:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DisplayVersion

c++ (on Clion) for loop stops in the middle with no errors (exit code 0) [duplicate]

When using CLion I have found the output sometimes cuts off.
For example when running the code:
main.cpp
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 1000; i++) {
printf("%d\n", i);
}
fflush(stdout); // Shouldn't be needed as each line ends with "\n"
return 0;
}
Expected Output
The expected output is obviously the numbers 0-999 on each on a new line
Actual Output
After executing the code multiple times within CLion, the output often changes:
Sometimes it executes perfectly and shows all the numbers 0-999
Sometimes it cuts off at different points (e.g. 0-840)
Sometimes it doesn't output anything
The return code is always 0!
Screenshot
Running the code in a terminal (i.e. not in CLion itself)
However, the code outputs the numbers 0-999 perfectly when compiling and running the code using the terminal.
I have spent so much time on this thinking it was a problem with my code and a memory issue until I finally realised that this was just an issue with CLion.
OS: Ubuntu 14.04 LTS
Version: 2016.1
Build: #CL-145.258
Update
A suitable workaround is to run the code in debug mode (thanks to #olaf).
The consensus is that this is an IDE issue. Therefore, I have reported the bug.
A suitable workaround is to execute the code in debug mode (no breakpoint required).
I will update this question, as soon as this bug is fixed.
Update 1
WARNING: You should not change information in registry unless you have been asked specifically by JetBrains. Registry is not in the main menu for a reason! Use the following solution at your own risk!!!
JetBrains have contacted me and provided a suitable solution:
Go to the Find Action Dialog box (CTRL+SHIFT+A)
Search for "Registry..."
Untick run.processes.with.pty
Should then work fine!
Update 2
The bug has been added here:
https://youtrack.jetbrains.com/issue/CPP-6254
Feel free to upvote it!

CMake Release made my code stop working properly

I have a C++ program which works well when I compile with no additional options. However, whenever I use cmake -DCMAKE_BUILD_TYPE=Release there is a very specific part of the code which stops working.
Concretely, I have an interface for a Boost Fibonacci Heap. I am calling this function:
narrow_band_.push(myObject);
And this function does the following:
inline void myHeap::push (myStruct & c) {
handles_[c.getIndex()] = heap_.push(c);
}
where heap_ is:
boost::heap::fibonacci_heap<myStruct, boost::heap::compare<compare_func>> heap_;
For some reason the heap_size is not being modified, therefore the rest of the code does not work because the next step is to extract the minimum from the heap and it is always empty.
In Debug mode it works ok. Thank you for your help.
EDIT - Additional info
I have also found this problem: I have a set of code which do simple math operations. In Release mode the results are incorrect. If I just do cout of a couple of variables to check their values, the result changes, which is still incorrect but quite strange.
I solved the problem. It was funny but in this case it was not initialization/timing issues common in the Release mode. It was that the return statement was missing in a couple of functions. In debug mode the output was perfect but in the release mode that failed. I had warnings deactivated, that is why I did not see it before.

QTCreator: GDB debugs code once, then drops to assembly

Using Qt 5.1.1 for Windows 32-bit (with MinGW 4.8), when debugging GDB wants to drop into dissassembly while debugging code after the first time.
I make a "Plain C++" project, insert some simple code:
int x = 5;
cout << x << endl;
return 0;
Build, and debug it with a breakpoint on first line. First time through it debugs just fine stepping through the code with "Step Over". Any debug session after that, it will drop into dissamebly view of ntdll when it hits cout (or anything else library related).
Operate By Instruction is not checked and there is debug information for my code. It works as expected once, then refuses to.
I can delete the build folder and the .pro.user file and the project still exhibits the same behavior after a new build. Even tried wiping my QTProject settings folder. There seems to be no way to debug just my code more than once without it wanting to drop into assembly instead of stepping over statements. If I make a new project, I can debug it normally once, then it starts behaving the same way.
Looking for a fix or suggestions of things to try.
Had a chance to go back...diffed the debugger log on the good initial vs sequential runs. Everything looks similar until I get to this in good run:
=thread-exited,id="2",group-id="i1"
sThread 2 in group i1 exited
~"[Switching to Thread 5588.0x239c]\n"
=thread-selected,id="1"
sThread 1 selected
Bad runs never have that. Later, this is unique to bad run:
>1272^done,threads=[{id="2",target-id="Thread 7148.0x242c",frame=
{level="0",addr="0x7792fd91",func="ntdll!RtlFindSetBits",args=
[],from="C:\\Windows\\system32\\ntdll.dll"},state="stopped"},
//LINES BELOW COMMON TO GOOD+BAD
{id="1",target-id="Thread 7148.0x1bbc",frame=
{level="0",addr="0x00401606",func="main",args=
[],file="..\\untitled8\\main.cpp",fullname=
"C:\\Users\\Andrew\\Desktop\\untitled8\\main.cpp",line="7"},
state="stopped"}],current-thread-id="1"*
Then once it hits the breakpoint, good run shows this:
*stopped,reason="end-stepping-range",frame={addr="0x00401620",func="fu0__ZSt4cout",args[],
file="..\untitled8\main.cpp",
fullname="C:\Users\Andrew\Desktop\untitled8\main.cpp",line="9"},
thread-id="1",stopped-threads="all"
Bad run shows this:
>*stopped,reason="signal-received",signal-name="SIGTRAP",signal-meaning="Trace/breakpoint trap",
frame={addr="0x7792000d",func="ntdll!LdrFindResource_U",args=[],
from="C:\\Windows\\system32\\ntdll.dll"},thread-id="2",stopped-threads="all"
dNOTE: INFERIOR SPONTANEOUS STOP sStopped.
dState changed from InferiorRunOk(11) to InferiorStopOk(14) [master]
dSIGTRAP CONSIDERED HARMLESS. CONTINUING.
sStopped: "signal-received"
>=thread-selected,id="2"
sThread 2 selected
<1283-thread-info
>1283^done,threads=[{id="2",target-id="Thread 7148.0x242c",frame=
{level="0",addr="0x7792000d",func="ntdll!LdrFindResource_U",args=[],
from="C:\\Windows\\system32\\ntdll.dll"},state="stopped"},
{id="1",target-id="Thread 7148.0x1bbc",
frame={level="0",addr="0x756a133d",func="KERNEL32!GetPrivateProfileStructA",
args=[],from="C:\\Windows\\syswow64\\kernel32.dll"},state="stopped"}],current-thread-id="2"
<1284-stack-list-frames 0 20
>1284^done,stack=[frame={level="0",addr="0x7792000d",func="ntdll!LdrFindResource_U",
from="C:\\Windows\\system32\\ntdll.dll"},
frame={level="1",addr="0x779af926",
func="ntdll!RtlQueryTimeZoneInformation",
from="C:\\Windows\\system32\\ntdll.dll"},frame={level="2",addr="0x75f45dd1",func="??"},
frame={level="3",addr="0x00000000",func="??"}]
<1285-stack-select-frame 0
<1286disassemble 0x7791fff9,0x77920071
<1287bb options:fancy,autoderef,dyntype vars: expanded:return,local,watch,inspect typeformats: formats: watchers:
>1285^done
>&"disassemble 0x7791fff9,0x77920071\n"
>~"Dump of assembler code from 0x7791fff9 to 0x77920071:\n"
>~" 0x7791fff9 <ntdll!LdrFindResource_U+60953>:\t"
>&"Cannot access memory at address 0x7791fff9\n"
>1286^error,msg="Cannot access memory at address 0x7791fff9"
sDisassembler failed: Cannot access memory at address 0x7791fff9
Looks like for some reason that extra thread is not exiting when expected and qtcreator/gdb convince themselves there are breakpoints in ntdll that I want to stop at.

Code::Blocks - strange return code

I run the following with Code::Blocks
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, world !!!!!!!";
return 0;
}
Now, there were some questions last night about how I knew my return value. I don't know if it's my version or not, but after the program runs on my version it says "Process returned v (0xv) execution time..." and etc where "v" is the returned value.
Now, here is what I'm asking, and this is as clear as I can make it.
When I run this, it returns value 1993075819 instead of 0. Also, the program doesn't run, all it does is show me the returned value.
Two things worthy of note:
AVG pops up everytime I try and do this, and reports it as a trojan
If I run the code without
cout << "Hello, world!!!!";
It returns 0 like it should and AVG does not pop up
How can I fix this?
(Code::Blocks 12.11)
The problem is not with your code, but with a false positive produced by AVG. The return code 1993075819 is because AVG intercepts the program and does not let it run.
You can report the false positive to AVG. Virus vendors are actually very good at fixing false positives reported by users. When I used to work at a company that produced lots of false positives (security related code that did funky things that triggered false positives), the turn-around was usually about a week.
In the mean time, if you use different compiler switches (e.g. optimized compile if it is not currently optimized or vice versa) there's a decent chance that the code you generate will not trigger the false positive.
You can also add your compiled program to the AVG safe list:
http://www.ehow.com/how_8192066_add-exceptions-avg.html
Disable AVG or configure it not to complain about your executable. For some reason the heuristics are misinterpreting some bit pattern in your executable as if it was a trojan and killing it before it starts. The result code that you get is from the intercepted program call (i.e. the antivirus) not from your program that is not even running.