#include <iostream>
#include <vector>
using namespace std;
typedef struct Record
{
std::string name;
bool isVisible;
int index;
}Record;
vector<Record> recordVector;
int main (int argc, char * const argv[])
{
Record tmpRecord = {"c++", true, 1};
for (int i = 0 ; i < 15; ++i) {
recordVector.push_back(tmpRecord);
}
return 0;
}
When I am debugging this and hover my cursor at recordVector variable to see the entire contents of this, its showing just 10(0-9) only, also its also not showing full contents in memory browser also. Although this vector has 15 contents in it.
Any clue for tweaking out this will be greatly appreciated.
Be sure you are using the "Debug" build configuration. Debug builds generate debug symbols and disable code optimization, otherwise the information shown by the debugger may be inaccurate.
You can found more info about this topic in the Mac OS X Reference Library.
Related
Suppose I have a complex C++ application that I need to debug with a lot of variables. I wanna avoid using std::cout and printf approaches (below there's an explaination why).
In order to explain my issue, I wrote a minimal example using chrono (This program calculates fps of its while cycle over time and increment i_times counter until it reaches 10k):
#include <chrono>
using chrono_hclock = std::chrono::high_resolution_clock;
int main(int argc, char** argv){
bool is_running = true;
float fps;
int i_times=0;
chrono_hclock::time_point start;
chrono_hclock::time_point end;
while(is_running){
start = chrono_hclock::now();
// Some code execution
end = chrono_hclock::now();
fps=(float)1e9/(float)std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count());
if(++i_times==10000) is_running=false;
}
return 0;
}
I would like to debug this program and watch for fps and i_times variables continuosly over time, without stopping execution.
Of course I can simply use std::cout, printf or other means to output variables values redirecting them to stdout or a file while debugging and those are OK for simple types, but I have multiple variables which data type are struct-based and it would be creepy, time expensive and code bloating to write instructions to print each one of them. Also my application is a realtime video/audio H.264 encoder streaming with RTSP protocol and stopping at breakpoints means visualizing artifacts in my other decoder application because the encoder can't keep up with the decoder (because the encoder hit a breakpoint).
How can I solve this issue?
Thanks and regards!
The IDE I'm currently using for developing is Visual Studio 2019 Community.
I'm using the Local Windows Debugger.
I'm open to using alternative open source IDEs like VSCode or alternative debugging methods to solve this problem and/or to not be confinated into using a specific IDE.
To watch for specific multiple variables in VS I use the built-in Watch Window. While debugging with LWD, I add manually variables by right-clicking them in my source code and click Add Watch. Then those are showed in the Watch Window (Debug-Windows-Watch-Watch 1):
However I can only watch this window contents once I hit a breakpoint I set inside the while cycle, thus blocking execution, so that doesn't solve my issue.
You can use nonblocking breakpoint. First add the breakpoint. Then click on breakpoint settings or right click and select action.
Now you add a message like any string that is suggestive for you. And in brackets include the values to show, for instance
value of y is {y} and value of x is {x}
In the image is shown the value of i when it hits the breakpoint. Check the "Continue code execution" so breakpoint will not block execution. The shape of your breakpoint will change to red diagonal square. You can add also specific conditions if you click the Conditions checkbox.
Now while debugging all these debug messages will be shown in the output window:
In the above image it is showing the following message:
the value of i is {i}
By checking the "Conditions" you can add specific conditions, for instance i%100==0 and it will show the message only if i is divisible by 100.
This time your breakpoint will be marked with a + sign, meaning it has condition. Now while debugging there will be shown the i only when divisible by 100, so you can restrict the output to some more meaningful cases
The strict answer is "no" but...
I think I understand what you're trying to accomplish. This could be done by dumping the watched variables into to shared memory which is read by 2nd process. A watch and a break point in the 2nd would allow you to see the values in Visual Studio without interrupting the original application.
A few caveats:
UAC must be admin on both sides to open the memory handle
This wouldn't work with pointers as the 2nd program only has access to the shared memory
Windows anti-virus went nuts for the first few times I
ran this but eventually calmed down
Worker application:
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <windows.h>
#include <chrono>
#include <thread>
PCWSTR SHARED_MEMORY_NAME = L"Global\\WatchMemory";
struct watch_collection // Container for everything we want to watch
{
int i;
int j;
int k;
};
using chrono_hclock = std::chrono::high_resolution_clock;
int main(int argc, char** argv)
{
bool is_running = true;
float fps;
int i_times = 0;
chrono_hclock::time_point start;
chrono_hclock::time_point end;
HANDLE map_file;
void* shared_buffer;
// Set up the shared memory space
map_file = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(watch_collection), SHARED_MEMORY_NAME);
if (map_file == NULL)
{
return 1; // Didn't work, bail. Check UAC level!
}
shared_buffer = MapViewOfFile(map_file, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(watch_collection));
if (shared_buffer == NULL)
{
CloseHandle(map_file); // Didn't work, clean up the file handle and bail.
return 1;
}
// Do some stuff
while (is_running) {
start = chrono_hclock::now();
for (int i = 0; i < 10000; i++)
{
for (int j = 0; j < 10000; j++)
{
for (int k = 0; k < 10000; k++) {
watch_collection watches { i = i, j = j, k = k };
CopyMemory(shared_buffer, (void*)&watches, (sizeof(watch_collection))); // Copy the watches to the shared memory space
// Do more things...
}
}
}
end = chrono_hclock::now();
fps = (float)1e9 / (float)std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
if (++i_times == 1000000) is_running = false;
}
// Clean up the shared memory buffer and handle
UnmapViewOfFile(shared_buffer);
CloseHandle(map_file);
return 0;
}
Watcher application:
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#pragma comment(lib, "user32.lib")
PCWSTR SHARED_MEMORY_NAME = L"Global\\WatchMemory";
struct watch_collection // Container for everything we want to watch
{
int i;
int j;
int k;
};
int main()
{
HANDLE map_file;
void* shared_buffer;
bool is_running = true;
watch_collection watches; // Put a watch on watches
// Connect to the shared memory
map_file = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, SHARED_MEMORY_NAME);
if (map_file == NULL)
{
return 1; // Couldn't open the handle, bail. Check UAC level!
}
shared_buffer = MapViewOfFile(map_file, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(watch_collection));
if (shared_buffer == NULL)
{
CloseHandle(map_file);
return 1;
}
// Loop forever
while (is_running)
{
CopyMemory((void*)&watches, shared_buffer, (sizeof(watch_collection)));
} // Breakpoint here
UnmapViewOfFile(shared_buffer);
CloseHandle(map_file);
return 0;
}
I have the following code which is a pretty simple test, but the VS refuses to run it:
stxxl::syscall_file OutputFile("Data/test.bin", stxxl::file::RDWR | stxxl::file::CREAT | stxxl::file::DIRECT);
typedef stxxl::VECTOR_GENERATOR<struct Rectangle, 8, 2, 524288>::result vector_type;
vector_type rects(&OutputFile);
the program produces a runtime error in a memory location in the 3rd line . What am I doing wrong? I'm compiling the program for 64-bit platforms. In the Debug mode if I press continue the program resumes and executes without problem.
Consider the following example:
#include <stxxl/io>
#include <stxxl/vector>
#include <iostream>
struct Rectangle {
int x;
Rectangle() = default;
};
int main() {
stxxl::syscall_file OutputFile("/tmp/test.bin", stxxl::file::RDWR |
stxxl::file::CREAT | stxxl::file::DIRECT);
typedef stxxl::VECTOR_GENERATOR<Rectangle, 8, 2, 524288>::result vector_type;
vector_type rects(&OutputFile);
Rectangle my_rectangle;
for (std::size_t i = 0; i < 1024 * 1024 * 1024; ++i)
rects.push_back(my_rectangle);
return 0;
}
An error can easily be provoked when there is not enough space left on the device. Can you post your runtime error?
Some background: I am trying to track a bug which is causing me major headaches. After many dead ends (see this question) I finally ended up with this code:
#include <thread>
#include <vector>
#include <iosfwd>
#include <sstream>
#include <string>
#include <windows.h>
int main()
{
SRWLOCK srwl;
InitializeSRWLock(&srwl);
for(size_t i=0;i<1000;++i)
{
std::vector<std::thread>threads;
for(size_t j=0;j<100;++j)
{
OutputDebugString(".");
threads.emplace_back([&](){
AcquireSRWLockExclusive(&srwl);
//Code below modifies the probability to see the bug.
std::this_thread::sleep_for(std::chrono::microseconds(1));
std::wstringstream wss;
wss<<std::this_thread::get_id();
wss.str();
//Code above modifies the probability to see the bug.
ReleaseSRWLockExclusive(&srwl);});
}
for(auto&t:threads){t.join();}
OutputDebugString((std::to_string(i)+"\n").data());
}
return 0;
}
When I run this code inside VS 2013 debugger the program hangs with an output like this one:
....................................................................................................0
....................................................................................................1
....................................................................................................2
...........................
Strangely enough, If I pause the debugger and inspect what is going on, one of the threads is inside AcquireSRWLockExclusive (in NtWaitForAlertByThreadId) apparently there is no reason why the program is hanging. When I click resume, the program happily continues and print some more stuff until it is blocked again.
Do you have any Idea what is going on here ?
Some more info:
As far as I can tell, this bug only exists on Windows 8.1.
I tried VS2013.4 and VS2015 RC.
I could reproduce it on two different computers under Windows 8.1.
One of the machine was formatted, the RAM, CPU and Disk tested (I thought of a malfunction because at first I could only observe the bug on this particular machine)
I could never reproduce it on Windows 7.
It may be useful to modify the code between the comments to observe the bug. When I added the microsecond sleep, I could at last reproduce the bug on another computer.
With VS2015 RC I could reproduce the same behavior with a simple std::mutex. On VS2013 however the SRWLOCK seems mandatory to observe the bug.
This issue is caused by an OS scheduler bug introduced in the spring 2014 update to Windows 8.1. A hotfix for this problem was released in May 2015 and available at https://support.microsoft.com/en-us/kb/3036169.
For me it looks like a bug in windows OS, I have different code variants that hangs using new Vista primitives under debugger in Win 8.1 / Server 2012R2 after April 2014 update. Also some thread pool wait function hangs too. Looks like it mostly tied to other thread finished execution at the moment of wait/lock. Here is the simple code that always hangs under debugger in NtWaitForAlertByThreadId() :
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#pragma optimize("",off)
VOID CALLBACK _WorkCallback(PTP_CALLBACK_INSTANCE Instance, PVOID pUser, PTP_WORK Work)
{
for (int i = 0; i < INT_MAX / 256; i++) {}
}
DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
for (int i = 0; i < INT_MAX / 256; i++) {}
return 0;
}
#pragma optimize("",on)
int _tmain(int argc, _TCHAR* argv[])
{
LONGLONG c = 0;
while(!_kbhit())
{
PTP_WORK ptpw = CreateThreadpoolWork(&_WorkCallback, NULL, NULL);
if (ptpw != NULL)
{
for(long i = 0; i < 3; i++) SubmitThreadpoolWork(ptpw);
CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
WaitForThreadpoolWorkCallbacks(ptpw, FALSE);
CloseThreadpoolWork(ptpw);
}
printf("%I64d \r", c++);
}
_getch();
return 0;
}
Unfortunately I have no idea where to report it to the Microsoft.
I have a weird problem. I have written some MEX/Matlab-functions using C++. On my computer everything works fine. However, using the institute's cluster, the code sometimes simply stops running without any error (a core file is created which says "CPU limit time exceeded"). Unfortunately, on the cluster I cannot really debug my code and I also cannot reproduce the error.
What I do know is, that the error only occurs for very large runs, i.e., when a lot of memory is required. My assumption is therefore that my code has some memoryleaks.
The only real part where I could think of is the following bit:
#include <vector>
using std::vector;
vector<int> createVec(int length) {
vector<int> out(length);
for(int i = 0; i < length; ++i)
out[i] = 2.0 + i; // the real vector is obviously filled different, but it's just simple computations
return out;
}
void someFunction() {
int numUser = 5;
int numStages = 3;
// do some stuff
for(int user = 0; user < numUser; ++user) {
vector< vector<int> > userData(numStages);
for(int stage = 0; stage < numStages; ++stage) {
userData[stage] = createVec(42);
// use the vector for some computations
}
}
}
My question now is: Could this bit produce memory leaks or is this save due to RAII (which I would think it is)? Question for the MATLAB-experts: Does this behave any different when run as a mex file?
Thanks
I have an issue with Eclipse Indigo complaining that methods of a class couldn't be resolved, but compiling anyway and working correctly (AFAIK). It's a very simple program. Here is Population.cpp:
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include "Population.h"
Population::Population() {
// TODO Auto-generated constructor stub
}
Population::~Population() {
// TODO Auto-generated destructor stub
}
void Population::initializePop(int numBits, int N) {
srand((unsigned)time(0));
for(int i=0; i<N; i++) {
x[i] = (char*) calloc(numBits, sizeof(char));
for(int j=0; j<numBits; j++) {
if( rand() < 0.5 )
x[i][j] = 0;
else
x[i][j] = 1;
}
}
}
char** Population::getX() {
return x;
}
void Population::printStuff() {
std::cout << "Whatever";
}
Now, I build that code and everything is fine. In another project within Eclipse, I'm calling this code like this:
#include <typeinfo>
#include <string.h>
#include <iostream>
#include "cute.h"
#include "ide_listener.h"
#include "cute_runner.h"
#include "Population.cpp"
void testPopulationGeneration() {
Population* p = new Population;
int N = 10;
int bits = 4;
char** pop;
ASSERTM("Population variable improperly initialized", dynamic_cast<Population*>(p));
std::cout << p->printStuff();
std::cout << "Ok...";
p->initializePop(bits, N);
pop = p->getX();
ASSERTM("Pop not correct size.", sizeof(pop) == 10);
}
As you can see I'm also running the CUTE plugin for TDD in C++. It doesn't complain when I declare p as type Population and the first assertion passes. I'm somewhat new to C++, but I did make sure to add the project that Population.cpp is from to the include path for the test project.
It's not a huge deal as it's not affecting anything obvious to me, but it's still very annoying. I don't see a situation where it should do this.
Thanks for any help!
Try this:
In your project explorer window, right click on your project -> Index -> Rebuild
This could be an indexing issue related to external #include headers not found. Follow the steps below and see if it helps:
Go to each of your custom #include (e.g. "cute.h") and press
F3 (i.e. "Show declaration"); see if it's able to access that file
or not; if not copy those files on some notepad
If the file is not accessible, then locate it paths in your
directory structure; e.g. "cute.h" and "a.h" are located at,
"C://Eclipse/MyWork/Workspace/Project/include_1" and
"ide_listener.h" is located
at,"C://Eclipse/MyWork/Workspace/Project/include_2", then copy both
the folder paths on some notepad
Inside Eclipse go to Project -> Properties -> C/C++ General ->
Paths and Sybmols; you will see several tabs as Includes,
Sybmols, Library Paths ...
Click Library Paths -> Add -> Workspace... -> <locate the above
folder paths> and press OK
Let the indexer rebuild; now again follow the step (1); hopefully
the files should be accessible
For future safety for larger files, go to Window -> Preferences ->
C/C++ -> Editor -> Scalability -> "Enable scalability mode when
..." and set the number of lines to some big number such as
500000 and press "OK";
The last step is needed, because when your file grows in line number and if exceeds the above number then eclipse will stop showing definitions for some "scalability" reasons, even though it would have indexed.
sizeof(pointer) returns the size of the pointer (4 on 32-bit systems and 8 on 64-bit), not the size of what it points to! Save the dimensions in the class, and add a function to return them.
Also, in initializePop shouldn't you allocate the actual X array?
X = calloc(N, sizeof(char *));
Or rather, you should use new for allocation since you are using C++:
X = new char* [N];
and later:
X[i] = new char [numbits];
Not that i'm any expert at all but i just had a similar problem using.empty for whatever reason it will work if you change char to string minor change but resolved the issue on my program