Memory leak with Mat in convertTo-function - opencv

I have some trouble with managing memory in my function. Valgrid says I'm having a memory leak after the convert-function. Could it be because of the data is not being properly released? I've tried to use temp-pointers, but my program either crashes or is not working properly. Have someone encountered this problem before?
this->images.push_back(new cv::Mat()); //ID
cv::threshold(*this->images[MASK], *this->images[ID], 0.0, 1.0, cv::THRESH_BINARY);
this->images[ID]->convertTo(*this->images[ID], CV_32SC1);
This is the valgrid output:
==5663== 64,339,996 bytes in 1 blocks are possibly lost in loss record 380 of 380
==5663== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5663== by 0x4E95117: cv::fastMalloc(unsigned long) (in /usr/local/lib/libopencv_core.so.2.4.9)
==5663== by 0x4F31F38: cv::Mat::create(int, int const*, int) (in /usr/local/lib/libopencv_core.so.2.4.9)
==5663== by 0x4F39CF9: cv::_OutputArray::create(cv::Size_<int>, int, int, bool, int) const (in /usr/local/lib/libopencv_core.so.2.4.9)
==5663== by 0x4EB9373: cv::Mat::convertTo(cv::_OutputArray const&, int, double, double) const (in /usr/local/lib/libopencv_core.so.2.4.9)
==5663== by 0x40D168: DataFrame::init() (DataFrame.cpp:68)
==5663== by 0x40C943: DataFrame::DataFrame(char const*, LeafClassifier*) (DataFrame.cpp:31)
==5663== by 0x414A19: DataHandler::loadFrame() (DataHandler.cpp:68)
==5663== by 0x406680: main (main.cpp:58)

please don't store pointers to Mat in your vector(or anywhere else !).
those things are refcounted internally, like smartpointers, and you're wrecking that by storing/copying pointers (a vector of pointers to smartpointers would sound silly anyway, no?).
use a plain vector<Mat>, trade some additional ~56 bytes per item against sound sleep tonight ;)

Related

Google Nearby Messages Crashed: AudioRecorderCallbackQueue on deallocation

I'm using Swift to use Google Nearby Messages library. I followed the sample code to setup the library. I'm using both bluetooth and microphone to test the function. I dealloc the publication/subscription in viewDidDisappear(). Basically it's two lines of code:
publication = nil
subscription = nil
However, when I dismiss the view controller, sometimes the whole app will crash. The stacktrace only shows that the crash has something to do with the audio. Here's part of the stacktrace:
Crashed: AudioRecorderCallbackQueue
0 libdispatch.dylib 0x18df39f60 _dispatch_barrier_sync_f_slow + 596
1 ProjectLibs 0x1037ad8e0 std::__1::vector<unsigned char, std::__1::allocator<unsigned char> >::vector(std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&) + 2808
2 ProjectLibs 0x1037ad8e0 std::__1::vector<unsigned char, std::__1::allocator<unsigned char> >::vector(std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&) + 2808
3 ProjectLibs 0x1037ad0f4 std::__1::vector<unsigned char, std::__1::allocator<unsigned char> >::vector(std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&) + 780
4 libsystem_blocks.dylib 0x18df7ea28 _Block_release + 144
Does anyone have any idea what may have caused the crash, and how to solve it or prevent the app from crash?
Thanks!
I set up an app to behave the way you have described yours as working. By enabling the logging, I notice that it is still sending messages for a brief period of time, which is likely where your crash is coming from.
You can enable logging with this command:
GNSMessageManager.setDebugLoggingEnabled(true)
By setting them to nil earlier in the process, I was able to get them to stop being sent before the viewcontroller was completely closed down.
The following does it at the soonest point possible (even before viewWillDisappear):
override func willMove(toParentViewController parent: UIViewController?) {
super.willMove(toParentViewController: parent)
if parent == nil {
publication = nil
subscription = nil
}
}

SIGBUS crash on Solaris 8

Compiled with g++ 4.7.4 on Solaris 8. 32 bit application. Stack trace is
Core was generated by `./z3'.
Program terminated with signal 10, Bus error.
\#0 0x012656ec in vector<unsigned long long, false, unsigned int>::push_back (this=0x2336ef4 <g_prime_generator>, elem=#0xffbff1f0: 2) at ../src/util/vector.h:284
284 new (m_data + reinterpret_cast<SZ *>(m_data)[SIZE_IDX]) T(elem);
(gdb) bt
\#0 0x012656ec in vector<unsigned long long, false, unsigned int>::push_back (this=0x2336ef4 <g_prime_generator>, elem=#0xffbff1f0: 2) at ../src/util/vector.h:284
\#1 0x00ae66d4 in prime_generator::prime_generator (this=0x2336ef4 <g_prime_generator>) at ../src/util/prime_generator.cpp:24
\#2 0x00ae714c in __static_initialization_and_destruction_0 (__initialize_p=1, __priority=65535) at ../src/util/prime_generator.cpp:99
\#3 0x00ae71c4 in _GLOBAL__sub_I_prime_generator.cpp(void) () at ../src/util/prime_generator.cpp:130
\#4 0x00b16a68 in __do_global_ctors_aux ()
\#5 0x00b16aa0 in _init ()
\#6 0x00640b10 in _start ()
(gdb) list
279
280 void push_back(T const & elem) {
281 if (m_data == 0 || reinterpret_cast<SZ *>(m_data)[SIZE_IDX] == reinterpret_cast<SZ *>(m_data)[CAPACITY_IDX]) {
282 expand_vector();
283 }
284 new (m_data + reinterpret_cast\<Z *>(m_data)[SIZE_IDX]) T(elem);
285 reinterpret_cast<SZ *>(m_data)[SIZE_IDX]++;
286 }
287
288 void insert(T const & elem) {
(gdb) ptype SZ
type = unsigned int
(gdb) ptype m_data
type = unsigned long long *
SIGBUS on Solaris is usually indicative of a misaligned access, but I am not sure if it is due to the casting going on an endianess issue
The SPARC data alignment requirements is most likely at issue.
The m_data field in the vector class is off by two fields that are used
to store the size and capacity of a vector.
You can debug this by displaying (printing or using the debugger) the pointer m_data and it's alignment.
One option is to supply a separate vector implementation
where the size and capacity fields are stored
in fields directly in the vector for porting this library utility.
Z3 interacts with memory alignment a few other places (but not overly many).
The main other potential places are in the watch lists (sat_solver and smt_context), and region memory allocators (region.h) and possibly in hash tables.

Swift compiler segmentation fault with generic recursive function

I've run into an interesting issue with the Swift compiler, which seems to be caused by a very simple generic function. I've got a workaround, but I'd really like to understand what the underlying issue is.
In my app I have a requirement to fade in some UICollectionViewCells in a given order, sequentially, with a slight overlap between the animations.
I've implemented this using the methods below. The revealCells method takes an array of cells. If the collection is empty, it simply returns. Otherwise it animates the fade-in on the first cell in the array, and then waits a certain amount of time before making a recursive call to itself, passing all the cells except the one it just animated.
Code below:
func revealCells(cells:[UICollectionViewCell],animationTime:NSTimeInterval,overlap:Double) {
if cells.count > 0 {
let firstCell = cells.first
UIView.animateWithDuration(0.3, animations: { () -> Void in
firstCell?.alpha = 1.0
let timeMinusOverlap = animationTime - overlap
let delayTime = dispatch_time(DISPATCH_TIME_NOW,Int64(timeMinusOverlap * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue(), { () -> Void in
self.revealCells(self.cdr(cells),animationTime: animationTime,overlap: overlap)
})
})
}
}
}
//Returns the collection passed into the function with its first element removed
//i.e the traditional LISP cdr function
func cdr<T>(input:[T]) -> [T] {
var rVal = [T]()
if input.count == 1 {
rVal.append(input.first!)
} else {
rVal = [T](input[1...input.count-1])
}
return rVal
}
All this works fine in the simulator. But when I try to archive the build, the swift compiler crashes with the message Swift Compiler Error Command failed due to signal: Segmentation fault 11. My setup is Xcode 6.3.1 (iOSSDK 8.3), and my min deployment target is 8.3.
Fixing the problem is trivial - if I just replace the code inside the dispatch_after with:
let newCells = [UICollectionViewCell](cells[1...cells.count-1])
self.revealCells(newCells,animationTime: animationTime,overlap: overlap)
the problem goes away. So it seems to be something to do with the generic function, or possibly something block related.
Stack trace is:
0 swift 0x000000010105ba18 llvm::sys::PrintStackTrace(__sFILE*) + 40
1 swift 0x000000010105bef4 SignalHandler(int) + 452
2 libsystem_platform.dylib 0x00007fff8725ef1a _sigtramp + 26
3 libsystem_platform.dylib 0x000000000000000f _sigtramp + 2027557135
4 swift 0x00000001021a98cb llvm::AsmPrinter::EmitFunctionBody() + 4379
5 swift 0x000000010116c84c llvm::ARMAsmPrinter::runOnMachineFunction(llvm::MachineFunction&) + 220
6 swift 0x0000000100d81d13 llvm::MachineFunctionPass::runOnFunction(llvm::Function&) + 99
7 swift 0x00000001024d5edf llvm::FPPassManager::runOnFunction(llvm::Function&) + 495
8 swift 0x00000001024d60cb llvm::FPPassManager::runOnModule(llvm::Module&) + 43
9 swift 0x00000001024d658f llvm::legacy::PassManagerImpl::run(llvm::Module&) + 975
10 swift 0x0000000100a09b41 performIRGeneration(swift::IRGenOptions&, swift::Module*, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, swift::SourceFile*, unsigned int) + 4369
11 swift 0x0000000100a09cb3 swift::performIRGeneration(swift::IRGenOptions&, swift::SourceFile&, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, unsigned int) + 51
12 swift 0x0000000100945687 frontend_main(llvm::ArrayRef<char const*>, char const*, void*) + 6647
13 swift 0x0000000100943ae6 main + 1814
14 libdyld.dylib 0x00007fff8a46b5c9 start + 1
(a long list of program arguments, which are mostly the names of file being compiled)
1. Running pass 'Function Pass Manager' on module '/Users/tolleyr/Library/Developer/Xcode/DerivedData/ParseTestQuiz-fgnfjkxxlyqfnrfrfntgtsjnrcfv/Build/Intermediates/ArchiveIntermediates/ParseTestQuiz/IntermediateBuildFilesPath/ParseTestQuiz.build/Release-iphoneos/ParseTestQuiz.build/Objects-normal/armv7/QuizQuestionViewController.o'.
2. Running pass 'ARM Assembly / Object Emitter' on function '#_TFC13ParseTestQuiz26QuizQuestionViewController13viewDidAppearfS0_FSbT_'
(the last part enabled me to figure out what code was causing the problem). The command being run was CompileSwift normal armv7
I'm going to file a radar for this, since the compiler itself is crashing , but thought I'd post it here in case anyone has an idea of what might be going on, or has run into the same issue.

convert MH_EXECUTE to MH_DYLIB (mach-o)

The problem:
I have 2 MH_EXECUTE iOS binary files (compiled, no source code).
Lets name them binary1 and binary2.
I try to switch between them before UIApplicationMain is called!
1 try
I successfully do this with binary1 and one dylib. So I try to convert MH_EXECUTE to MH_DYLIB.
step 1
creating iOS Application binary1
#import <dlfcn.h>
int main(int argc, char * argv[])
{
NSLog(#"binary1 -> Hello, World!");
void *handle = dlopen([[[NSBundle mainBundle] pathForResource:#"binary2" ofType:nil] cStringUsingEncoding:NSUTF8StringEncoding], RTLD_NOW);
if (handle)
{
NSLog(#"DLOPEN is OK!");
}
else
{
NSLog(#"!OK ... --> %s", dlerror());
}
return 0;
}
creating iOS Application binary2
int main(int argc, char * argv[])
{
NSLog(#"binary2 -> Hello, World!");
return 0;
}
When I run binary1 I get:
step 2
Lets see the difference MH_EXECUTE vs MH_DYLIB
fullscreen
as we can see the main difference here is File Type: MH_EXECUTE vs MH_DYLIB
Lets change them and run binary1 again.
After change the result was out of address space
step 3
Lets see Load Commands
fullscreen
* in dylib there is NO __PAGEZERO segment
* dylib __TEXT segment VM address == 0 but in binary2 == 0000000100000000
So lets patch them too ... (patched: __TEXT, ___DATA and __LINKEDIT)
After run binary1 i get malformed mach-o image: segment __PAGEZERO overlaps load commands
step 4
I successfully removed __PAGEZERO from Load Commands now binary looks like dylib:
fullscreen
But on start binary1 I get BAD_ACCESS
Exception Type: EXC_BAD_ACCESS (SIGBUS)
Exception Subtype: KERN_PROTECTION_FAILURE at 0x00000001019e0010
Triggered by Thread: 0
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 dyld 0x0000000120016d78 ImageLoaderMachOCompressed::rebase(ImageLoader::LinkContext const&) + 892
1 dyld 0x0000000120016c24 ImageLoaderMachOCompressed::rebase(ImageLoader::LinkContext const&) + 552
2 dyld 0x0000000120010c8c ImageLoader::recursiveRebase(ImageLoader::LinkContext const&) + 132
3 dyld 0x000000012001039c ImageLoader::link(ImageLoader::LinkContext const&, bool, bool, bool, ImageLoader::RPathChain const&) + 176
4 dyld 0x00000001200088e0 dyld::link(ImageLoader*, bool, bool, ImageLoader::RPathChain const&) + 180
5 dyld 0x000000012000df68 dlopen + 684
6 libdyld.dylib 0x0000000194e65b94 dlopen + 68
7 binary1 0x00000001000b7e18 main (main.m:16)
8 libdyld.dylib 0x0000000194e66a04 start + 0
Any idea ???
You're getting BAD_ACCESS because you removed __PAGEZERO and thus invalidated the rebasing opcodes. Keep __PAGEZERO but nullify it. I similarly converted an executable into a shared library and it's loading fine on iOS and macOS.

activeX control crash on alt+tab

I've implemented an Delphi acitveX control. Everything runs fine on html. After that, I embed that activeX in an MFC application. It's good, except that when I test it, if I alt+tab to another windows(Chrome, for example...) and alt+tab back to my application, it just crashed.
I know that this is a non-clear question, but I have no clues. Any clues to solve this situation? What may go wrong or what events I should take a look at?
Thanks.
Edit 1:
This is what I got when I use spy++ on it.
<04518> 00100B7C S WM_ACTIVATE fActive:WA_INACTIVE fMinimized:False hwndPrevious:(null)
<04519> 00100B7C S WM_ACTIVATETOPLEVEL fActive:False dwThreadID:0025F40C
<04520> 00100B7C R WM_ACTIVATETOPLEVEL
Edit 2:
This is what I got from call stack when I break all at the time it hangs
mfc100d.dll!CThreadSlotData::GetThreadValue(int nSlot) Line 248 C++
mfc100d.dll!CThreadLocalObject::GetData(CNoTrackObject * (void)* pfnCreateObject) Line 420 + 0x11 bytes C++
mfc100d.dll!CThreadLocal<AFX_MODULE_THREAD_STATE>::GetData() Line 179 + 0xd bytes C++
mfc100d.dll!AfxGetModuleThreadState() Line 477 + 0x11 bytes C++
mfc100d.dll!afxMapHWND(int bCreate) Line 289 + 0x5 bytes C++
mfc100d.dll!CWnd::FromHandlePermanent(HWND__ * hWnd) Line 324 + 0x7 bytes C++
mfc100d.dll!AfxWndProc(HWND__ * hWnd, unsigned int nMsg, unsigned int wParam, long lParam) Line 405 + 0x9 bytes C++
mfc100d.dll!AfxWndProcBase(HWND__ * hWnd, unsigned int nMsg, unsigned int wParam, long lParam) Line 420 + 0x15 bytes C++
Edit 3:
I'm using Visual studio 2010, the call stack tell that application hangs in this function, line 2, from afxtls.cpp. Please anyone shed some lights on how to solve this.
inline void* CThreadSlotData::GetThreadValue(int nSlot)
{
EnterCriticalSection(&m_sect);
ASSERT(nSlot != 0 && nSlot < m_nMax);
ASSERT(m_pSlotData != NULL);
ASSERT(m_pSlotData[nSlot].dwFlags & SLOT_USED);
ASSERT(m_tlsIndex != (DWORD)-1);
if( nSlot <= 0 || nSlot >= m_nMax ) // check for retail builds.
{
LeaveCriticalSection(&m_sect);
return NULL;
}
CThreadData* pData = (CThreadData*)TlsGetValue(m_tlsIndex);

Resources