What's causing this code to increase memory usage - c++

I have the following sample program (C++):
#include <iostream>
#include <gtkmm.h>
#include <boost/thread.hpp>
using namespace std;
Gtk::Window * window;
Glib::Dispatcher dispatcher;
void do_updates();
void load_layout();
int x;
int main(int argc, char ** argv)
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "nl.mycroes.test");
window = new Gtk::Window;
window->set_default_size(200, 200);
Gtk::Label * label = new Gtk::Label("label");
window->add(*label);
dispatcher.connect(&load_layout);
window->show_all();
boost::thread t = boost::thread(do_updates);
app->run(*window);
Gtk::Widget * child = window->get_children().front();
delete child;
return 0;
}
void load_layout()
{
stringstream layout;
layout << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
<< endl << "<interface>"
<< endl << "<object class=\"GtkWindow\" id=\"window\">"
<< endl << "<child>"
<< endl << "<object class=\"GtkLabel\" id=\"text\">"
<< endl << "<property name=\"visible\">True</property>"
<< endl << "<property name=\"can_focus\">False</property>"
<< endl << "<property name=\"label\">" << x << "</property>"
<< endl << "</object>"
<< endl << "</child>"
<< endl << "</object>"
<< endl << "</interface>";
Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create_from_string(layout.str());
Gtk::Window * win;
builder->get_widget("window", win);
std::vector<Gtk::Widget *> old_children = window->get_children();
Gtk::Widget * child = old_children.front();
window->remove();
delete child;
std::vector<Gtk::Widget *> new_children = win->get_children();
child = new_children.front();
child->reparent(*window);
delete win;
}
void do_updates()
{
for (x = 0; x < 10000; x++)
{
boost::this_thread::sleep(boost::posix_time::milliseconds(1));
dispatcher();
}
}
If I keep an eye on the memory usage (watch -n 1 "grep ^Vm /proc/\$(pgrep GtkLeakTest)/status") it keeps increasing, but I don't know what's staying around in memory. Also, valgrind doesn't report any leaks at all, which makes it seem like I'm properly cleaning everything up...
I actually tried if I had to recursive delete the window child, because this is a testcase for a program where I'm loading a larger galde layout and that also leaks, but I tried and and logically doesn't make a difference because I don't put nested components in the window. Any hints are appreciated!

Related

Qt - Bytearray with empty entries?

I'm working on a simple function which is able to return a int in Qt using information sent to a comport.
I'm using the QSerialPort class which returns a QBytearray.
The problem is i seem (on occasion) to get empty entries in the array that QSerialPort.readAll returns. This makes me unable to convert the bytearray to an int.
The basic functionality is: Ask for Arduino to send either temperature or humidity.
Qt code:
#include <QCoreApplication>
#include <QSerialPortInfo>
#include <QSerialPort>
#include <iostream>
#include <string>
#include <windows.h>
#include <math.h>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString comPort = "COM6";
QSerialPortInfo ArduinoInfo(comPort);
cout << "Manufacturer: " << ArduinoInfo.manufacturer().toStdString() << endl;
cout << "Product Identifier: " << ArduinoInfo.productIdentifier() << endl;
cout << "Vendor Identifier: " << ArduinoInfo.vendorIdentifier() << endl;
QSerialPort Arduino(ArduinoInfo);
Arduino.setBaudRate(QSerialPort::Baud9600);
Arduino.open(QSerialPort::ReadWrite);
Sleep(1000);
if(Arduino.isDataTerminalReady())
cout << "Great Sucess" << endl;
char sending = 'H';
cout << sending << endl;
Arduino.write(&sending, 1);
//int maxSize = Arduino.bytesAvailable();
while(!Arduino.waitForReadyRead()){}
Sleep(100);
QByteArray rawDataArry = Arduino.readAll();
cout << "Shit has been read." << endl;
// Form here on its just write functions, used for debug
cout << "rawData:" << endl;
for(int i=0; i < rawDataArry.size(); i++)
cout << "[" << i << "] "<< rawDataArry[i] << endl;
cout << "All data:" << endl;
for(char s:rawDataArry){
cout << s;
}
cout << endl;
cout << "Converted data:" << endl;
bool ok;
int returnVar = rawDataArry.toInt(&ok, 10);
cout << returnVar << endl;
cout << "Convertion Status:" << ok;
Arduino.close();
return a.exec();
}
The Arduino code is super simple.
#include <dht.h>
dht DHT;
#define PIN_7 7
void setup() {
Serial.begin(9600);
}
void loop()
{
String impString;
while(Serial.available() != 1);
impString = Serial.readString();
DHT.read11(PIN_7);
if(impString == "T")
{
int temp = DHT.temperature;
Serial.println(temp);
}
else if(impString == "H")
{
int humid = DHT.humidity;
Serial.println(humid);
}
emptyReceiveBuf();
delay(100);
}
void emptyReceiveBuf()
{
int x;
delay(200); // vent lige 200 ms paa at alt er kommet over
while (0 < Serial.available())
{
x = Serial.read();
}
}
Terminal monitor displays:
Looks like rawDataArry.size() is returning 4, so that means there ARE 4 bytes in the array. However, when you call rawDataArry[i] it returns a char. Not every char value can be represented as an ascii character. Which is why the last 2 bytes appear empty.
Instead you should try to convert each char to a value that shows the decimal/hex representation of the byte instead of the ascii representation.
Alternatively, you could convert those 4 bytes right to an int and be done with it:
//Big Endian
quint32 myValue(0);
for(int i=0; i<4; i++)
myValue = myValue + (quint8(rawDataArry.at(i)) << (3-i)*8);
//myValue should now have your integer value
I ended up using a member of QByteArray to clean up the widespaces in the array!
It looks something like this!
bool ok;
int returnVal;
do
{
Arduino.write(&imputChar, 1); // Arduino input Char
Arduino.waitForReadyRead();
QByteArray rawDataArry(Arduino.readAll()); // Empties buffer into rawDataArry
QByteArray dataArray(rawDataArry.simplified()); // Removes all widespaces!
returnVal = dataArray.toInt(&ok, 10); // Retuns ByteConvertion - &OK is true if convertion has completed - Widespaces will ruin the conversion
qDebug() << "Converted data:";
qDebug() << returnVal;
qDebug() << "Convertion Status:" << ok;
}while(ok != 1);
return(returnVal);

QT frame visualisation

Currently started to work with qt and found some bug in my code, and I can't understand where it comes from. Maybe you will see and explain why it happens.
Here is main.cpp code part which changes shutter from 3000 to maximum:
if (camera.test_cam->liveFrameReady())
{
camera.visualizeFrame(camera.test_cam->liveFrame());
camera.set_shutter(0, 1, 3000 + i * 200);
controlWidget->update(camera.test_cam->liveFrame());
i++;
}
The code works slowly(1 fps ), because of the camera.visuzlizeFrame() method:
void OsCam::visualizeFrame(Common::FrameHandle hFrame)
{
void* buffer_ptr = this->getFrameData(hFrame);
int width = hFrame->dataType()->width();
int height = hFrame->dataType()->height();
cv::Mat m(height, width, CV_8UC3, (int*)buffer_ptr);
cv::imshow("test image", m);
cv::waitKey(1);
}
Gui interface shows the camera frame in real time, test image from visualizeFrame at the background
Actionally, I don't need to call this method (I used it just to be sure that I can read the memory and I used opencv because I am more familiar with it).
But if I get rid of this camera.visuzlizeFrame() my gui becomes white and does not give any response.
Even if I use cv::waitKey or Sleep functions, nothing happens to the gui.
void ControlWidget::update(Common::FrameHandle hFrame)
{
try
{
QImage img((uchar*)hFrame->buffer()->data(), hFrame->dataType()->width(), hFrame->dataType()->height(), QImage::Format::Format_RGB888);
QSize standart_size = QSize(hFrame->dataType()->width() / 3, hFrame->dataType()->height() / 3);
QPixmap rectPxmp = QPixmap::fromImage(img).scaled(standart_size);
this->camera_1->setPixmap(rectPxmp);
this->camera_2->setPixmap(rectPxmp);
cv::waitKey(300);
}
catch (GeneralException& e)
{
std::cout << e.what() << std::endl;
}
}
Shall I go to QThreads? One thread for reading the buffer and another one for visualization of gui?
Thank you!
some additional code:
void* OsCam::getFrameData(Common::FrameHandle hFrame)
{
bool displayFrameData = false;
void* pFrameData = NULL;
try
{
if (hFrame)
{
if (displayFrameData)
{
// display information about the frame
cout << "Frame index: " << hFrame->frameIndex();
cout << "Frame timestamp: " << hFrame->timestamp();
// display information about the frame "data type"
DataTypeHandle hDataType = hFrame->dataType();
cout << "Frame size in bytes: " << hDataType->frameSizeInBytes() << endl;
cout << "Width in pixels: " << DataType::width(hDataType) << endl;
cout << "Height in rows: " << DataType::height(hDataType) << endl;
cout << "Bit depth: " << DataType::bitDepth(hDataType) << endl;
cout << "Bytes/line (stride): " << DataType::stride(hDataType) << endl;
// display the frame video format
VideoDataType::Format videoFormat = VideoDataType::format(hDataType);
cout << "Video format: " << VideoDataType::formatString(videoFormat).c_str() << endl;
// get a pointer to the frame data
}
pFrameData = hFrame->buffer()->data();
}
}
catch (GeneralException& e)
{
cout << e.what() << endl;
}
return pFrameData;
}
and main (I changed it a little bit) :
int main(int argc, char **argv)
{
QApplication app(argc, argv);
ControlWidget *controlWidget = new ControlWidget;
//controlWidget->show();
try
{
OsCam camera;
int i = 0;
for (int j = 0; j<10000 ; j++)
{
if ((camera.test_cam->liveFrameReady()))
{
Common::FrameHandle loaded = camera.test_cam->liveFrame()->clone();
camera.visualizeFrame(loaded);
controlWidget->update(loaded);
camera.set_shutter(0, 1, 3000 + i * 200);
loaded->~Frame();
}
i++;
}
}
catch (GeneralException& e)
{
std::cout << e.what() << std::endl;
int a;
std::cin >> a;
return 1;
}
}
After cv::named_window

Getting CrtIsValidHeapPointer Error when trying to release memory [C++]

I have an exercise and I need to create an Engine class and a Car class.
Those are parts of my code:
Car.cpp
Car::Car()
{
_engine = new Engine();
_manufacturer = new char[10];
_prod_year = 0;
_color = new char[10];
}
Car::~Car()
{
// Releasing allocated memory
delete[] _manufacturer;
delete[] _color;
delete _engine;
}
void Car::print(void) const
{
(*_engine).print();
cout << "\n" << endl;
cout << "Manufacturer:" << _manufacturer << "\n" << endl;
cout << "Production Year:" << _prod_year << "\n" << endl;
cout << "Color:" << _color << endl;
}
Car.h
class Car
{
Engine * _engine;
char * _manufacturer;
int _prod_year;
char * _color;
public:
/*
* Creates a Car with the default set of attributes.
*/
Car();
virtual ~Car();
inline Engine * GetEngine() { return _engine; }
void SetEngine(Engine * engine) { _engine = engine; }
inline char * GetManufacturer(){ return _manufacturer; }
void SetManufacturer(char * manufacturer){_manufacturer = manufacturer;}
inline int GetProdYear() { return _prod_year; }
void SetProdYear(int prod_year) { _prod_year = prod_year; }
inline char * GetColor() { return _color; }
void SetColor(char * color) { _color = color; }
void print(void) const;
};
Engine.h
class Engine
{
/*
Represents an Engine with the following attributes:
* int Hourse Power
* char * Manufacturer
* int Production Year
*/
int _horse_power;
char * _manufacturer;
int _prod_year;
public:
Engine();
virtual ~Engine();
int GetHorsePower() { return _horse_power; }
void SetHorsePower(int horse_power) { _horse_power = horse_power; }
char * GetManufacturer(){ return _manufacturer; }
void SetManufacturer(char * manufacturer){_manufacturer = manufacturer;}
int GetProdYear() { return _prod_year; }
void SetProdYear(int prod_year) { _prod_year = prod_year; }
void print() const;
};
Exc.cpp
Engine engine;
engine.SetHorsePower(150);
cout << "Current Horse Power: " <<engine.GetHorsePower()<<endl;
char * manufacturer = new char[strlen("VP") +1];
strcpy(manufacturer, "VP");
engine.SetManufacturer(manufacturer);
cout << "Current Manufacturer: " << engine.GetManufacturer() << endl;
engine.SetProdYear(1995);
cout << "Current Production Year: " << engine.GetProdYear() << endl;
cout << "\n ------------- Printing engine details -------------\n" << endl;
engine.print();
Car car;
car.SetEngine(&engine);
cout << "Current Engine: " << endl;
(*car.GetEngine()).print();
char * car_manufacturer = new char[strlen("Toyota") + 1];
car_manufacturer = { "Toyota" };
car.SetManufacturer(car_manufacturer);
cout << "Current Car Manufacturer: " << car.GetManufacturer() << endl;
car.SetProdYear(2010);
cout << "Current Car Production Year: " << car.GetProdYear() << endl;
char * color = new char[strlen("Yellow") + 1];
color = { "Yellow" };
car.SetColor(color);
cout << "Current Car Color: " << car.GetColor() << endl;
cout << "\n ------------- Printing car details -------------\n" << endl;
car.print();
My program is doing ok until it gets to ~Car and then I get "CrtIsValidHeapPointer".
Can someone tell me what I did wrong?
Thx.
SOLUTION
Engine * engine = new Engine;
engine->SetHorsePower(150);
cout << "Current Horse Power: " << engine->GetHorsePower()<<endl;
char * manufacturer = new char[strlen("VP") +1];
strcpy(manufacturer, "VP");
engine->SetManufacturer(manufacturer);
cout << "Current Manufacturer: " << engine->GetManufacturer() << endl;
engine->SetProdYear(1995);
cout << "Current Production Year: " << engine->GetProdYear() << endl;
cout << "\n ------------- Printing engine details -------------\n" << endl;
engine->print();
Car car;
car.SetEngine(engine);
cout << "Current Engine: " << endl;
car.GetEngine()->print();
char * car_manufacturer = new char[strlen("Toyota") + 1];
strcpy(car_manufacturer, "Toyota");
car.SetManufacturer(car_manufacturer);
cout << "Current Car Manufacturer: " << car.GetManufacturer() << endl;
car.SetProdYear(2010);
cout << "Current Car Production Year: " << car.GetProdYear() << endl;
char * color = new char[strlen("Yellow") + 1];
strcpy(color, "Yellow");
car.SetColor(color);
cout << "Current Car Color: " << car.GetColor() << endl;
cout << "\n ------------- Printing car details -------------\n" << endl;
car.print();
return 0;
In the Car constructor you dynamically allocate an Engine and assign to _engine.
Then in your main program you do
car.SetEngine(&engine);
thereby changing _engine to point to an object you haven't allocated dynamically with new, and losing the original pointer and giving you a memory leak.
So in the Car destructor you try to delete a pointer you haven't allocated with new leading to undefined behavior.
There are also problems with the strings, where you do thing like
char * car_manufacturer = new char[strlen("Toyota") + 1];
car_manufacturer = { "Toyota" };
That first allocates memory, and you assign a pointer to that memory to car_manufacturer. Then directly afterward you make car_manufacturer point somewhere else again losing the pointer to the memory you have allocated and a new memory leak. Besides you then make set the pointer in the car object to the string literal "Toyota" which again is a pointer to memory you have not allocated with new[] so doing delete[] again leads to undefined behavior.
Solving the problem with the strings are easy, even if you don't want to use std::string (which is the recommended solution), and that is to copy the string instead of reassigning the pointer:
char * car_manufacturer = new char[strlen("Toyota") + 1];
strcpy(car_manufacturer, "Toyota");
To solve the first problem with the engine, you need to allocate the new engine dynamically too, if you have to call SetEngine.
In your Set function you should also free the memory already allocated, so you don't have memory leaks.

error C2228: left of '.printStats' must have class/struct/union

So I recently decided to pick up programming again and went with C++. Tried to make an adventurer class, but I seem to be running into some trouble. Here are my files:
Adventurer.h:
#ifndef __Adventurer_H_INCLUDED__ //if Adventurer.h hasn't been included yet...
#define __Adventurer_H_INCLUDED__ //#define this so the compiler knows it has been included
class Adventurer
{
private:
int hp, mp, str, agi, magic, armour;
public:
Adventurer(){}
void printStats();
}
#endif
Adventurer.cpp:
#include <iostream>
#include "Adventurer.h"
Adventurer::Adventurer()
{
hp = 50;
mp = 25;
str = 5;
agi = 5;
magic = 5;
armour = 5;
}
void Adventurer::printStats()
{
cout << "HP = " << hp << "\n\n";
cout << "MP = " << mp << "\n\n";
cout << "str = " << str << "\n\n";
cout << "agi = " << agi << "\n\n";
cout << "magic = " << magic << "\n\n";
cout << "armour = " << armour << "\n\n";
}
RPG_Game.cpp:
// my first program in C++
#include <iostream>
#include <string>
#include "Adventurer.h"
;using namespace std;
int main()
{
cout << "Hello Adventurer! What is your name? \n";
string advName;
cin >> advName;
cout << "\nYour name is " << advName << "!";
Adventurer *adv = new Adventurer();
cout << adv.printStats();
delete adv;
system(pause);
}
Let's look at the errors in your code
First, in your Adventurer.h, put a semicolon (;) after the class.
Next, in that same class, you have
Adventurer(){}
change this to
Adventurer();
Then, in your RPG_Game.cpp , change
cout << adv.printStats();
to
adv->printStats() ;
When using pointers, you need to use -> and not .
And lastly,
system(pause);
should be
system( "pause" );
Now, try running your code.
Also, you might find this helpful.

C++ Removing the command-line

when i run the compieled .exe-file it shows the commandline, and I wish to remove it.. But I don't know nothing about C++, so I wonder how one can do it?
This is not my script... Just so you know.
#include <iostream>
#include <windows.h>
using namespace std;
typedef long (*GetFunctionCount) (void) __attribute__((stdcall));
typedef long (*GetFunctionInfo)(int, void*&, char*&) __attribute__((stdcall));
typedef void (*Setup)(char*,char*,long,long,char*) __attribute__((stdcall));
int main(int argc, char** argv) {
HMODULE libsmart = LoadLibrary("./libsmart.dll");
cout << "Library: " << libsmart << '\n';
cout << "GetFunctionCount: " << (void*)GetProcAddress(libsmart, "GetFunctionCount") << '\n';
cout << "GetFunctionInfo: " << (void*)GetProcAddress(libsmart, "GetFunctionInfo") << '\n';
GetFunctionCount count = (GetFunctionCount) GetProcAddress(libsmart, "GetFunctionCount");
GetFunctionInfo info = (GetFunctionInfo) GetProcAddress(libsmart, "GetFunctionInfo");
int exports = count();
cout << "#Exports = " << count() << '\n';
for (int i = 0; i < exports; i++) {
char* def = new char[1024];
void* addr;
info(i,addr,def);
cout << '\t' << addr << " = " << def << '\n';
delete def;
}
cout << "Starting SMART...\n";
Setup setup = (Setup) GetProcAddress(libsmart, "std_setup");
setup((char*)"http://world19.runescape.com/", (char*)",f5", 765, 503,(char*)"");
while (true) Sleep(1000);
return 0;
}
#define _WIN32_WINNT 0x0500
#include <iostream>
#include <windows.h>
using namespace std;
typedef long (*GetFunctionCount) (void) __attribute__((stdcall));
typedef long (*GetFunctionInfo)(int, void*&, char*&) __attribute__((stdcall));
typedef void (*Setup)(char*,char*,long,long,char*) __attribute__((stdcall));
int main(int argc, char** argv) {
HWND hWnd = GetConsoleWindow();
ShowWindow( hWnd, SW_HIDE );
HMODULE libsmart = LoadLibrary("./libsmart.dll");
cout << "Library: " << libsmart << '\n';
cout << "GetFunctionCount: " << (void*)GetProcAddress(libsmart, "GetFunctionCount") << '\n';
cout << "GetFunctionInfo: " << (void*)GetProcAddress(libsmart, "GetFunctionInfo") << '\n';
GetFunctionCount count = (GetFunctionCount) GetProcAddress(libsmart, "GetFunctionCount");
GetFunctionInfo info = (GetFunctionInfo) GetProcAddress(libsmart, "GetFunctionInfo");
int exports = count();
cout << "#Exports = " << count() << '\n';
for (int i = 0; i < exports; i++) {
char* def = new char[1024];
void* addr;
info(i,addr,def);
cout << '\t' << addr << " = " << def << '\n';
delete def;
}
cout << "Starting SMART...\n";
Setup setup = (Setup) GetProcAddress(libsmart, "std_setup");
setup((char*)"http://world19.runescape.com/", (char*)",f5", 765, 503,(char*)"");
while (true) Sleep(1000);
return 0;
}
Should work. Don't forget the definition at the top.
If you wish to remove the part that shows the commandline, any line that starts with cout << is showing something to the screen.
However, the command line is primarily stored in argv, and I don't see any reference to that in your program.
You will want to compile and link it to the windows subsystem, rather than the console subsystem.