How to handle memory leaks? - qt

I'm not that familiar to memory handling, but i am currently working on a Qt project (c++), developing an app for Symbian devices, using the Qt Nokia SDK.
Platform: Windows 7
1'st question:
If i create a pushbutton like this:
QPushButton *button = new QPushButton(parent);
Do i have to delete it? (I think no, since it is part of the UI, but correct me if i'm wrong).
2'nd question:
How can i find a memory leak, do you know of any good programs that can help me with this?
I've tried using Nokia Analyzer tool, but when i run atool:
atool.exe -lf build armv5 udeb -f phoneMeomoryLog
i just get
Build type: udeb Build platform: armv5 Data gathering mode: log to
file Allocation call stack size: 40 Free call stack size: 0 Deferred
free: feature disabled Heap corruption check (guard blocks): feature
disabled AnalyzeTool : Error, creating/reading makefiles.
Hope someone can answer me.
Thanks in advance

1'st question : No you don't have to delete it. It will be deleted when the parent is deleted. So you have to delete the parent which is probably a form or dialog.
When you create the dialog with Qt::WA_DeleteOnClose flag Qt deletes this widget when the widget has accepted the close event. So you will not have any memory leaks.
So create your dialog with this flag and add your widgets as you are doing now and you will be fine.
2'nd question: If you are running on linux use valgrind.
example : valgrind --tool=memcheck --leak-check=yes ./myprogramname
valgrind has many options you can use for fine tuning.
Also using *unique_ptr* or *auto_ptr* if you are using older c++ or QScopedPointer are good programming techniques to avoid memory leaks.

The answer to your first Q is No. It seems that unlike windows standard GUI Objects, in Qt you should not delete it. It is being released when your main window is being closed.
You can use microsoft's memory link detector embedded at VS. Find more in this link.

Both "It is being released when your main window is being closed." and "The parent just releases the UI resources, not the memory !!! – hsalimi " are wrong. The parent keeps a list of its children and will delete them when it is destructed itself. This has nothing to do with "UI resources" or "main window", it's normal QObject behaviour. std::auto_ptr is neither needed nor useful here either.

Well, I have no experience in Qt Nokia SDK, but based on my C++ knowledge.
Yes. Everything created by new should be later freed. A pointer cannot free itself and C++ doesn't offer any garbage collector.
There are several ways. For example, check how many new's you're doing and how many delete's. For each new there should be a delete somewhere. Check the memory used: if memory used only grows and never (or not often) decreases, then you're not handling memory correctly. Make sure you're deleting any allocated resources on destructors.
To avoid this you can use auto-pointers

Related

How can I increase the maximum number of lines ("window height") in a Qt console application?

I'm writing a quick&dirty number crunching test, using a Qt console application.
It prints several thousand lines, but the number of lines displayed in the console seems to be limited to about 300. This means that at the end I can no longer scroll back to the beginning of my printout.
How can I raise this limit? I found nothing in the project settings.
Or is it completely impossible, as the console window is controlled solely by my operating system?
It's important for me to launch the program directly from Qt creator, so a solution where I use a batch script or similar trick to run my program is not preferable.
Does a solution even exist, or am I forced to switch to a Qt GUI application where I create my own console out of a QTextEdit widget?
The number of lines displayed and the number of lines in the buffer is a property of the operating system. You can change this. How to do this depends on your OS.

KDE Taskbar Progress

I am trying to show a progress in the taskbar of the plasma desktop using the KDE Frameworks. In short, it want to do the same thing as dolphin, when it copies files:
I'm kinda stuck, because I don't even know where to get started. The only thing I found that could be useful is KStatusBarJobTracker, but I don't know how to use it. I could not find any tutorials or examples how to do this.
So, after digging around, and thanks to the help of #leinir, I was able to find out the following:
Since Plasma 5.6 KDE supports the Unitiy DBus Launcher-API, which can be used, for example, to show progress
I found a post on AskUbuntu that explains how to use the API with Qt
The real problem is: This only works, if you have a valid desktop file in one of the standard locations! You need to pass the file as parameter of the DBus message to make it work.
Based on this information, I figured out how to use it and created a GitHub repository, that supports cross platform taskbar progress, and uses this API for the linux implementation.
However, here is how to do it anyways. It should work for KDE Plasma and the Unity desktop, maybe more (haven't tried any others):
Create a .desktop file for your application. For test purpose, this can be a "dummy" file, that could look like this:
[Desktop Entry]
Type=Application
Version=1.1
Name=MyApp
Exec=<path_to>/MyApp
Copy that file to ~/.local/share/applications/ (or wherever user specific desktop files go on your system)
In your code, all you need to do is execute the following code, to update the taskbar state:
auto message = QDBusMessage::createSignal(QStringLiteral("/com/example/MyApp"),
QStringLiteral("com.canonical.Unity.LauncherEntry"),
QStringLiteral("Update"));
//you don't always have to specify all parameters, just the ones you want to update
QVariantMap properties;
properties.insert(QStringLiteral("progress-visible"), true);// enable the progress
properties.insert(QStringLiteral("progress"), 0.5);// set the progress value (from 0.0 to 1.0)
properties.insert(QStringLiteral("count-visible"), true);// display the "counter badge"
properties.insert(QStringLiteral("count"), 42);// set the counter value
message << QStringLiteral("application://myapp.desktop") //assuming you named the desktop file "myapp.desktop"
<< properties;
QDBusConnection::sessionBus().send(message);
Compile and run your application. You don't have to start it via the desktop file, at least I did not need to. If you want to be sure your application is "connected" to that desktop file, just set a custom icon for the file. Your application should show that icon in the taskbar.
And thats basically it. Note: The system remembers the last state when restarting the application. Thus, you should reset all those parameters once when starting the application.
Right, so as it turns out you are right, there is not currently a tutorial for this. This reviewboard request, however, shows how it was implemented in KDevelop, and it should be possible for you to work it out through that :) https://git.reviewboard.kde.org/r/127050/
ps: that there is no tutorial now might be a nice way for you to hop in and help out, by writing a small, self contained tutorial for it... something i'm sure would be very much welcomed :)

libuv event loop in qt

Is there a way without using multiple threads?
I found this https://stackoverflow.com/a/17329626/4014896
But i don't get how it works. Shouldn't it cause 100% CPU usage in the example?
and how can I embed it, for example, into QT?
there is also this: https://github.com/svalaskevicius/qt-event-dispatcher-libuv
But there is no documentation at all.
But from my looks it seems to be something that translates from example QSocket to uv_tcp_socket which is not what I'm searching for.
In short - you'll either need to merge the two event loops or use separate threads and sync the event handlers manually..
The first link you pasted shows how to process libuv events that have happened since the last invocation. The while stated there will use ~100% CPU if there are no events dispatched (as it will just keep polling).
The second link (qt-event-dispatcher-libuv) is a project I've created to tackle the same problem. It does, however, work as you described - by using libuv to handle Qt's event loop (and by doing that - merges the two event loops into one).
To use it you'd just need to register the event dispatcher in your application using http://qt-project.org/doc/qt-5/qcoreapplication.html#setEventDispatcher. An example where this library is used - https://github.com/svalaskevicius/qtjs-generator/blob/master/src/runner/main.cpp#L179
There is still one catch using this approach - while it works very well on linux, there are some problems on OS X as the Qt's Cocoa platform support plugin handles some Cocoa's event loop operations and doesn't provide a nice API to merge it as well (currently its updating them one its freed up after a small timeout so there is some (barely?) noticeable lag to handle the GUI events) - I was planning to port the platform support plugin to be able to integrate it as well but that's still in future. And I haven't tested it on windows yet :)
An alternative solution could probably be to try to merge the two loops from another direction that I've done - instead of making Qt to use libuv, libuv's api could be provided that uses Qt's handlers - although it requires a considerable amount of work as well.
Please let me know if there is any more info I could provide.
Regards,

tcltk block input while processing in r

RGTK2 block user input while processing its explain how to block user input using RGTK2 but I dont know how to add that code to my GUI code, im using tcltk. What I want same like in RGTK2 block user input while processing but using tcltk2
I use this code to run button "filter cluster" and the command function is filter (function to do something)
tkpack(tkbutton(f4, text='Filter Cluster', command=filter), side='left',padx= 5, pady = 20)
In tcltk, you would use tkgrab.set on a non-responsive window and tkfocus on a window that has a binding on the <Key> event that prevents further processing. An inconspicuous tkframe is great for that sort of thing — set it to size 1×1, but ensure it is on the screen — as it has no default behaviour to get in the way. (You'll also want to make a bunch of cosmetic changes, such as marking the widgets as disabled and setting the cursor to watch.) In 8.6, there's tk busy (call with tcl("tk","busy",…) since the Tcl tk command appears to not have a convenient mapping) which makes this all much easier (though I don't know if/how that's mapped into R). The simplest way to release a grabbed window is to destroy it, but you can also tkgrab.release.
Do not use a global grab. They're easy to get wrong and can cause you a lot of grief. (If you insist, you're strongly recommended to make mouse activity cancel it and to test very thoroughly. Locking up your display is not a pleasant experience!) The default local grabs are less of a problem, since you can switch to another program and kill off a stuck app if necessary.
The full documentation for Tk (and Tcl) is online; pick the version of the docs for the version of the library that you're using, probably 8.5, hopefully 8.6 ('cos it has some nice extras) and possibly 8.4 (old skool!) As the R documentation for tcltk says, you can invoke anything in Tcl or Tk through tcl(…), passing in the words of the command name and arguments as many strings… (Tcl is a naturally var-args language and uses that extensively.) The limited scope of the default convenience mapping should not hinder you substantively.
General advice, not so closely related to your question
Most Tk programmers try to write their code to not lock users out that way if possible. You get a better user experience if you can keep the GUI responsive and instead just temporarily disable (via the state option on most reactive widgets) the parts that would otherwise trigger reentrancy problems for the duration. (The long-running processing might be also event-driven, or put in another thread, or even delegated to a sub-process. Just remember, Tk GUIs are strictly single threaded — the implementation assumes this very deeply, though it's possible to have wholly independent apps in different threads, if rather hairy to get working right — so you've got to come back to the GUI thread to update anything in the GUI.)

Finch Sound Engine Memory Leak

I want to access some sounds in different classes and can be read and change the pitch values of each sound in multiple classes. Then i use extern FISound *mySound in my application delegate methods and loaded them in my view controller. It is working like a charm but the problem is there is an always memory leaks for [FIDecoder decodeSampleAtPath:error]
Leaked Object # Address Size Responsible Library Responsible Frame
FISample,1 0x76e9030 32 Bytes Musizs -[FIDecoder decodeSampleAtPath:error:]
NSConcreteData,1 0x76e7100 32 Bytes Foundation +[NSData(NSData) allocWithZone:]
NSConcreteData,1 0x737b080 32 Bytes Foundation +[NSData(NSData) allocWithZone:]
FISample,1 0x76e81c0 32 Bytes Musizs -[FIDecoder decodeSampleAtPath:error:]
Is somebody have problem like that?? Thank you.
The library code looks good to me, even after checking with Instruments. Can you post a short sample code that exhibits the leak? Also, how do you add the manual release calls to the source? The library uses ARC, so that manual memory management calls should be illegal. Do you use the library the right way, by referencing the whole Xcode project, or do you just import the “naked” source files?
XCode 4 detects many possible memory leaks with Finch. This is because
Finch is not properly naming its methods according to memory management guidelines.
Methods that create objects must begin their method name
with "new", "alloc", "copy", or "mutableCopy".
See:
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html
For example, decodeSampleAtPath should be renamed to "allocDecodeSampleAtPath".
And anything that uses this method must then release it.
There are many methods in Finch that don't do this, and they all should be fixed.

Resources