Decrease retain count While ARC mode is Enabled - malloc

I am new to iOS Developing , when I am using below code the retain count reaches to 3 and app will be crash,
AsyncronousUIImage *image=[[AsyncronousUIImage alloc] init];
[image loadImageFromURL:imageURL inImageView:templateView];
image.delegate=self;
[templateScroll addSubview:templateView];
I have ARC enable mode, I am using xcode 4.6.
getting the error:
malloc: * error for object 0xa293dd0: pointer being freed was not allocated
* set a breakpoint in malloc_error_break to debug
Any Help Appreciated.

If you are using ARC, then the image will be released once it leaves the scope of the current function. It looks like you are using an asynchronous method with that variable. So, the image is released by the time the async code has received the data and is trying to set it.
When using ARC, you need to make sure that you are holding on to variables that are needed in other parts of your code, or at least pass them on to other objects that will hold on to them.

Related

Getting error "attempting to detach while still running code" when calling JavaVm->DetachCurrentThread [duplicate]

I have an Android app that uses NDK - a regular Android Java app with regular UI and C++ core. There are places in the core where I need to call Java methods, which means I need a JNIEnv* for that thread, which in turn means that I need to call JavaVM->AttachCurrentThread() to get the valid env.
Previously, was just doing AttachCurrentThread and didn't bother to detach at all. It worked fine in Dalvik, but ART aborts the application as soon as a thread that has called AttachCurrentThread exits without calling DetachCurrentThread. So I've read the JNI reference, and indeed it says that I must call DetachCurrentThread. But when I do that, ART aborts the app with the following message:
attempting to detach while still running code
What's the problem here, and how to call DetachCurrentThread properly?
Dalvik will also abort if the thread exits without detaching. This is implemented through a pthread key -- see threadExitCheck() in Thread.cpp.
A thread may not detach unless its call stack is empty. The reasoning behind this is to ensure that any resources like monitor locks (i.e. synchronized statements) are properly released as the stack unwinds.
The second and subsequent attach calls are, as defined by the spec, low-cost no-ops. There's no reference counting, so detach always detaches, no matter how many attaches have happened. One solution is to add your own reference-counted wrapper.
Another approach is to attach and detach every time. This is used by the app framework on certain callbacks. This wasn't so much a deliberate choice as a side-effect of wrapping Java sources around code developed primarily in C++, and trying to shoe-horn the functionality in. If you look at SurfaceTexture.cpp, particularly JNISurfaceTextureContext::onFrameAvailable(), you can see that when SurfaceTexture needs to invoke a Java-language callback function, it will attach the thread, invoke the callback, and then if the thread was just attached it will immediately detach it. The "needsDetach" flag is set by calling GetEnv to see if the thread was previously attached.
This isn't a great thing performance-wise, as each attach needs to allocate a Thread object and do some internal VM housekeeping, but it does yield the correct behavior.
I'll try a direct and practical approach (with sample code, without use of classes) answering this question for the occasional developer that came up with this error in android, in cases where they had it working and after a OS or framework update (Qt?) it started to give problems with that error and message.
JNIEXPORT void Java_com_package_class_function(JNIEnv* env.... {
JavaVM* jvm;
env->GetJavaVM(&jvm);
JNIEnv* myNewEnv; // as the code to run might be in a different thread (connections to signals for example) we will have a 'new one'
JavaVMAttachArgs jvmArgs;
jvmArgs.version = JNI_VERSION_1_6;
int attachedHere = 0; // know if detaching at the end is necessary
jint res = jvm->GetEnv((void**)&myNewEnv, JNI_VERSION_1_6); // checks if current env needs attaching or it is already attached
if (JNI_EDETACHED == res) {
// Supported but not attached yet, needs to call AttachCurrentThread
res = jvm->AttachCurrentThread(reinterpret_cast<JNIEnv **>(&myNewEnv), &jvmArgs);
if (JNI_OK == res) {
attachedHere = 1;
} else {
// Failed to attach, cancel
return;
}
} else if (JNI_OK == res) {
// Current thread already attached, do not attach 'again' (just to save the attachedHere flag)
// We make sure to keep attachedHere = 0
} else {
// JNI_EVERSION, specified version is not supported cancel this..
return;
}
// Execute code using myNewEnv
// ...
if (attachedHere) { // Key check
jvm->DetachCurrentThread(); // Done only when attachment was done here
}
}
Everything made sense after seeing the The Invocation API docs for GetEnv:
RETURNS:
If the current thread is not attached to the VM, sets *env to NULL, and returns JNI_EDETACHED. If the specified version is not supported, sets *env to NULL, and returns JNI_EVERSION. Otherwise, sets *env to the appropriate interface, and returns JNI_OK.
Credits to:
- This question Getting error "attempting to detach while still running code" when calling JavaVm->DetachCurrentThread that in its example made it clear that it was necessary to double check every time (even though before calling detach it doesn't do it).
- #Michael that in this question comments he notes it clearly about not calling detach.
- What #fadden said: "There's no reference counting, so detach always detaches, no matter how many attaches have happened."

Data race in MFC in afxCurrentResourceHandle

we have an issue in MFC-based application related to “current MFC state” and threads. In main thread we call VisualManager, because we want to have fancy toolbars. The call ends up in CMFCVisualManagerOffice2007::OnUpdateSystemColors function located inside afxvisualmanageroffice2007.cpp, which changes “current resource handle” by calling AfxSetResourceHandle function. This function gets “current module state” and changes “current resource handle” from MyApp.exe to mfc140u.dll. This is fine, because assets for VisualManager are located in that DLL and the change will be restored back to MyApp.exe in all cases.
However, what is not fine is that we spawn a new thread just before call to VisualManager (by using AfxBeginThread), this thread needs to load some strings from string table (by using CString class), but it sometimes fails to do so. It fails because there is race with main thread about AFX_MODULE_STATE::m_hCurrentResourceHandle variable. The thread expect it to be set to MyApp.exe, but the main thread changes it to mfc140u.dll and back, the “current resource handle” is effectively a global variable.
So, my questions are: 1) Are we doing something obviously wrong managing our MFC-based threads? Should we somehow copy or protect the “module state” so our new thread is immune to the change main thread is doing? Should aim MFC to create something like per-thread variable / state? 2) I believe Microsoft is wrong here, changing what is effectively a global variable and screwing other threads expectations, VisualManager should obtain the handle and pass it to all its functions as a parameter. Am I right?
EDIT:
Hi guys #iinspectable, #cha, I have an update, sorry it took so long. Steps to reproduce: Open Visual Studio 2015 Update 3, Create new MFC application through the wizard, make sure it has the "Project style" and "Visual style and colors" selected as "Office" and "Office 2007 (Blue theme)". Open file afxvisualmanageroffice2007.cpp from MSVS folder and put 4 break-points into CMFCVisualManagerOffice2007::OnUpdateSystemColors function where it calls AfxSetResourceHandle. Open file MFCApplication1.cpp in your newly created project folder and put this code [1] into CMFCApplication4App::InitInstance function just before CMainFrame* pMainFrame = new CMainFrame;, put break-point into this thread proc.
Now build and run this MFC application in debug mode, on each break-point hit, use freeze thread and thaw thread functions from Threads window, so you will arrange main thread in the middle of CMFCVisualManagerOffice2007::OnUpdateSystemColors function just after setting the global variable using AfxSetResourceHandle function and the worker thread before CStringT::LoadString. Now the load string will fail because it is looking for it inside mfc140ud.dll instead of using resource chain and MFCApplication1.exe.
I believe this is Microsoft's bug (changing global variable for a while), my code-base is full of innocent CString::LoadString calls which rely on carefully and correctly constructed resource chain with various plug-in DLLs and with an .exe at the end. If this is not Microsoft's bug then it is my bug relying on MFC on providing me a usable resource chain. I would need to create my own resource-chain-like functionality and use it everywhere when loading strings and other stuff from resources.
// [1]
AFX_THREADPROC thread_proc = [](LPVOID pParam){
CString str;
str.LoadString(IDS_CAPTION_TEXT);
UINT ret = 0;
return ret;
};
::AfxBeginThread(thread_proc, (LPVOID)nullptr);
// Same result with ::AfxBeginThread(CRuntimeClass*) overload.

Can't release the ID3DX11Effect pointer?

I use Effect framework in my demo.
here are my defination in header file
ID3D11Buffer* m_pVertexBuffer;
ID3D11Buffer* m_pIndexBuffer;
ID3D11InputLayout* m_pInputLayout;
ID3DX11Effect* m_pFx;
ID3DX11EffectTechnique* m_pTechnique;
ID3DX11EffectMatrixVariable* m_pFxWorldViewProj;
I release them as follow
void HillsDemo::UnLoadContent()
{
if (m_pVertexBuffer) m_pVertexBuffer->Release();
if (m_pIndexBuffer) m_pIndexBuffer->Release();
if (m_pInputLayout) m_pInputLayout->Release();
if (m_pTechnique) m_pTechnique->Release();
if (m_pFx) m_pFx->Release();
}
then I run the demo,when I close the demo window, there is an error which means HillsDemo has stopped working.Why?Then I delete the lineif (m_pFx) m_pFx->Release();,there is no error. So is releasing the m_pFx make the error?
I view the documents of Effect11 https://github.com/Microsoft/FX11/wiki/Effects-11, there are on the document:
The following types are now derived from IUnknown: ID3DX11EffectType, ID3DX11EffectVariable, I3DX11EffectPass, ID3DX11EffectTechnique, ID3DX11EffectGroup. Note that these objects do not follow standard COM reference-counting rules and they are released when the parent ID3DX11Effect is released. This is mostly to simplify use of Effects 11 from managed languages.
Does it means that I should only release the m_pFx rather than release both m_pFx and m_pTechnique? Any ideas?
I assume you are using the latest version of Effects 11 from GitHub rather than the legacy DirectX SDK copy based on your reference to the project wiki.
You should really look at using ComPtr instead of raw pointers to COM objects. In the case of Effects 11, you'd just use them for ID3DX11Effect instances. You should stick with 'raw pointers' for ID3DX11EffectType, ID3DX11EffectVariable, I3DX11EffectPass, ID3DX11EffectTechnique, and ID3DX11EffectGroup. Don't bother calling Release on these raw pointers as the lifetime controlled by the ID3DX11Effect.
Something like:
Microsoft::WRL::ComPtr<ID3D11Buffer> m_pVertexBuffer;
Microsoft::WRL::ComPtr<ID3D11Buffer> m_pIndexBuffer;
Microsoft::WRL::ComPtr<ID3D11InputLayout> m_pInputLayout;
Microsoft::WRL::ComPtr<ID3DX11Effect> m_pFx;
ID3DX11EffectTechnique* m_pTechnique;
ID3DX11EffectMatrixVariable* m_pFxWorldViewProj;
void HillsDemo::UnLoadContent()
{
m_pVertexBuffer.Reset();
m_pIndexBuffer.Reset();
m_pInputLayout.Reset();
m_pFx.Reset();
m_pTechnique = nullptr;
pFxWorldViewProj = nullptr;
}

program crashes at wglmakecurrent

I am using opengl in a MFC application in visual studio 2008.
and there my project crashes at wglmakecurrent saying:
Access violation reading location
This happens only for a certain case so this is probably not a driver issue. And also I have checked in another machine where the same error occurs.
The error occurs at wglMakeCurrent(m_hDC,m_hRC) in the following function:
void CCETIGLView::Convert2D(CPoint win, GLdouble * objx,
GLdouble * objy, GLdouble * objz)
{
if((m_hDC) && (m_hRC))
{
wglMakeCurrent(m_hDC,m_hRC);
}
The parameters are of following types:
HGLRC m_hRC;
HDC m_hDC;
Tthey are obtained from a glview class which is a child class of cview.
It returns 0 for GetLastError() when I check wglMakeCurrent function.
This happens when rendering a certain option and other options work fine.
I am using single thread therefore multi threading issue also does not count.
This test
if((m_hDC) && (m_hRC))
only makes sense if it is made sure that m_hDC and m_hRC are initialized to 0 upon class creation, so that one can actually tell, that they're initialized. Probably you're not doing this, so those variables contain non-zero garbage and hence are misinterpreted as being initialized with valid handles.
Add constant initialization to the constructor
CCETIGLView::CCETIGLView() :
m_hDC(0), m_hRC(0)
{
// ...

C++ MultiThreading with visual studio express 2010 Forms Application

I am developing a Windows forms application which connects to a piece of hardware, acquires a lot of data (~1 GSample/sec), processes it, and spits it out to the screen upon a button click. I am now trying to automate the process in a loop that can be started/stopped at any time so I can monitor it whilst tweaking the input to the acquisition hardware. I thinks it's clear that I need to do this on a separate thread, but I'm having a heck of a time trying to do this in c++/cli - I have found a number of good examples using MFC, which is not supported by Express.
Specifically: My task is to press a button which is handled in Form1.h, to call a function in my main file Acquisition.cpp which contains the following code (currently an infinite loop)
void Form1::realTimeUpdate()
{
// live is a boolean variable set by a button on the form
while(live)
{
displayVariance(getVar(getQuadratures(100),nbrSamples));
}
}
I wish to execute this code in a separate thread so that the main program can listen for the user request to stop the operation. Without threading, I currently have to forcefully quit the program (or set it to run a fixed number of times) to stop it.
Is there any suggestions how I might go about running this code on a separate thread?
I've (unsuccessfully) tried a few things already:
Modifying the example given in This Microsoft Example. Problem: requires /clr:oldSyntax option which is incompatible with the other 1300 lines of code in the program.
Trying to do what I'd do in Java (Declare a global thread and start/stop it from any point in the code. Problem: Compiler won't let me declare a global System::Threading.Thread
this beautiful example. Problem: Requires MFC.
Any suggestions would be greatly appreciated!
You can use a BackgroundWorker or a Thread to handle this. You'll need to make sure that the portion of your work that updates the UI is marshaled back to the UI thread, however.
Here is a tutorial on threading in C++/CLI.
For the record, upon Reed's suggestion about using a BackgroundWorker, I sifted through the code at the bottom of this page and modified my code so that:
It created a new backgroundWorker BGWorker in which BGWorker->DoWork() called my realTimeUpdate() function.
A button on the main Form calls either RunWorkerAsync() or CancelAsync() depending on whether or not the process is running (checked by a boolean flag in my main program).
The realTimeUpdate() function is now passed a BackgroundWorker - realTimeUpdate(BackgroundWorker^ worker, DoWorkEventArgs ^ e) After each calculation is complete within the internal loop, it calls worker->ReportProgress(result) function. In the BGWorker->ProgressChanged() function a separate function, upDataUI(int) draws the result on the main form.
Thanks again for the help.

Resources