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
Related
I am using ecCodes library in my project, and I have encountered an issue that memory is not freed between reading the files.
The minimal example representing the problem is this (and is basically a combination of those two library API usage examples [1](https://confluence.ecmwf.int/display/ECC/grib_get_keys) [2]:
#include <string>
#include <vector>
#include <iostream>
#include "eccodes.h"
int main() {
std::string filenames[] = {"../data/era5_model.grib", "../data/era5_model2.grib", "../data/era5_model3.grib",
"../data/era5_model4.grib"};
std::vector<long> vec = {};
for (auto & filename : filenames) {
FILE* f = fopen(filename.c_str(), "r");
int err = 0;
codes_handle* h;
while ((h = codes_handle_new_from_file(nullptr, f, PRODUCT_GRIB, &err)) != nullptr) {
long k1 = 0;
err = codes_get_long(h, "level", &k1);
vec.push_back(k1);
}
codes_handle_delete(h);
fclose(f);
}
std::cout << vec[52];
return 0;
}
In the example the program reads 4 identical ERA5 files, each of size 1.5GB. Before opening new file previous one is closed with codes_handle_delete() and fclose().
Therefore, the expected behaviour would be for the memory usage to stay at about 1.5GB. However, in reality the memory usage steadily increases to about 6.5GB and is freed when program closes (see screenshot below).
This particular example has been run on CLion with CMake (Release configuration), but the issue occurs with every other configuration and also in my other Rust project which calls ecCodes with FFI.
The library seems well tested and supported so it seems unlikely that it is a library bug. Therefore, is that an expected behaviour or is my code wrong? If the latter, how can I correct it?
I am using Ubuntu 21.04 and ecCodes 2.20.0 installed with apt
So I contacted the library authors and realized that I have not read this example carefully enough.
For the ecCodes to correctly free the memory codes_handle should be deleted every time it is created (analogically to how you should free the memory every time you alloc it). Therefore in my example codes_handle_delete() should be INSIDE the while loop:
while ((h = codes_handle_new_from_file(nullptr, f, PRODUCT_GRIB, &err)) != nullptr) {
long k1 = 0;
err = codes_get_long(h, "level", &k1);
vec.push_back(k1);
codes_handle_delete(h);
}
After that change memory usage is almost unnoticeable.
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;
}
So I am making a game, an ASCII dungeon explorer and I had a plan to get the window size and scale the display the inventory beside the dungeon. I went on google to find a function that would return the window size so I can print the inv on the side... The parts that are commented out is the code that I found and so I tried to put it in my main.cpp just to try it out. I planned to use other functions that I found to get the max size of the window and to set the size. This code that I pasted into my code was giving me loads of errors when I went to run the game, somewhere around 180 errors from a header file called wingdi.h. I googled a bit more and found people changing some definitions in the project properties which I tried and it gave me about 130 errors from different headers included in . Someone said that one of the variables is already declared in windows.h and the person that asked that question should change it to something else so I changed csbi to my_csbi, both didn't work. Some people also said it was a problem with the code so I decided to just leave it for now, and go back to my old code and do something else for now (I was getting frustrated, lol). I commented it all out, hoping to come back to it later. When I tried to run my game with all of that code gone, it gave me the same errors. Do I have to reinstall Visual Studio 2015? Starting my code from scratch or changing some definitions?
#include <iostream>
#include <conio.h>
//#include <Windows.h>
#include "GameSystem.h"
using namespace std;
int main()
{
//int x = 0;
//int y = 0;
//CONSOLE_SCREEN_BUFFER_INFO my_csbi;
//GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &my_csbi);
//x = my_csbi.srWindow.Right -my_csbi.srWindow.Left + 1;
//y = my_csbi.srWindow.Bottom -my_csbi.srWindow.Top + 1;
//printf("columns: %d\n", x);
//printf("rows: %d\n", y);
GameSystem gameSystem("level1.txt");
gameSystem.playGame();
printf("Enter any key to exit...\n");
int tmp;
cin >> tmp;
return 0;
}
I am fairly new to programming so I'm sorry if my question is stupid or "simple" and if that offended you in some shape or form. :)
Thanks, Bulky.
EDIT: All the "solutions" others got didn't work for me and I decided to ask this because after I commented out all that code, my old code didn't even run (it was perfect before).
You never include <WinGdi.h> directly. You always include <Windows.h>, which pulls in the required headers implicitly.
The GDI functions (from <WinGdi.h>) aren't going to do you any good if you are writing a console application. The GetConsoleScreenBufferInfo function is probably what you want to be using, but it is not a GDI function. It is a kernel function. Again, although it is technically declared in <WinCon.h>, you are not supposed to include that header directly. Just include <Windows.h>.
The following code works fine for me
(other than the fact that std::cin doesn't actually work for "enter any key to exit..."):
#include <iostream>
#include <conio.h>
#include <Windows.h>
using namespace std;
int main()
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
int x = csbi.srWindow.Right - csbi.srWindow.Left + 1;
int y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
printf("columns: %d\n", x);
printf("rows: %d\n", y);
printf("Enter any key to exit...\n");
int tmp;
cin >> tmp;
return 0;
}
Output:
columns: 90
rows: 33
Enter any key to exit...
If it does not work for you, one of the following must be true:
1. The problem resides in "GameSystem.h", which you have not shown us.
(It is fineāin the future, please post code as text, not pictures.)
2. You have created the wrong type of project (recreate a new project using the Win32 Console Application template).
3. There is something wrong with your installation of Visual Studio (try reinstalling).
#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.
I am working with an implementation of merge sort. I am trying with C++ Visual Studio 2010 (msvc). But when I took a array of 300000 integers for timing, it is showing an unhandled stackoverflow exception and taking me to a readonly file named "chkstk.asm". I reduced the size to 200000 and it worked. Again the same code worked with C-free 4 editor (mingw 2.95) without any problem while the size was 400000. Do you have any suggestion to get the code working in Visual Studio?
May be the recursion in the mergesort is causing the problem.
Problem solved. Thanks to Kotti for supplying the code. I got the problem while comparing with that code. The problem was not about too much recursion. Actually I was working with a normal C++ array which was being stored on stack. Thus the problem ran out of stack space. I just changed it to a dynamically allocated array with the new/delete statements and it worked.
I'm not exactly sure, but this may be a particular problem of your implementation of yor merge sort (that causes stack overflow). There are plenty of good implementations (use google), the following works on VS2008 with array size = 2000000.
(You could try it in VS2010)
#include <cstdlib>
#include <memory.h>
// Mix two sorted tables in one and split the result into these two tables.
void Mix(int* tab1, int *tab2, int count1, int count2)
{
int i,i1,i2;
i = i1 = i2 = 0;
int * temp = (int *)malloc(sizeof(int)*(count1+count2));
while((i1<count1) && (i2<count2))
{
while((i1<count1) && (*(tab1+i1)<=*(tab2+i2)))
{
*(temp+i++) = *(tab1+i1);
i1++;
}
if (i1<count1)
{
while((i2<count2) && (*(tab2+i2)<=*(tab1+i1)))
{
*(temp+i++) = *(tab2+i2);
i2++;
}
}
}
memcpy(temp+i,tab1+i1,(count1-i1)*sizeof(int));
memcpy(tab1,temp,count1*sizeof(int));
memcpy(temp+i,tab2+i2,(count2-i2)*sizeof(int));
memcpy(tab2,temp+count1,count2*sizeof(int));
free(temp);
}
void MergeSort(int *tab,int count) {
if (count == 1) return;
MergeSort(tab, count/2);
MergeSort(tab + count/2, (count + 1) /2);
Mix(tab, tab + count / 2, count / 2, (count + 1) / 2);
}
void main() {
const size_t size = 2000000;
int* array = (int*)malloc(sizeof(int) * size);
for (int i = 0; i < size; ++i) {
array[i] = rand() % 5000;
}
MergeSort(array, size);
}
My guess is that you've got so much recursion that you're just running out of stack space. You can increase your stack size with the linker's /F command line option. But, if you keep hitting stack size limits you probably want to refactor the recursion out of your algorithm.
_chkstk() refers to "Check Stack". This happens in Windows by default. It can be disabled with /Gs- option or allocating reasonably high size like /Gs1000000. The other way is to disable this function using:
#pragma check_stack(off) // place at top header to cover all the functions
Official documentation.
Reference.