Trying to delete object with non-zero reference count.

When my program exits, the title appears. Does it represent my memory leak?

Probably. It is hard to tell without more information.

do you have any method about checkthe itk memory lack ?

I remember that VTK can bring up a dialog with a message similar to “Trying to delete object with non-zero reference count”. But I don’t think ITK does that. @blowekamp @mihail.isakov Do you agree?

ITK has the warning here

LightObject::~LightObject()
{
  /**
   * warn user if reference counting is on and the object is being referenced
   * by another object.
   */
  if (m_ReferenceCount > 0)
  {
    // A general exception safety rule is that destructors should
    // never throw.  Something is wrong with a program that reaches
    // this point anyway.  Also this is the least-derived class so the
    // whole object has been destroyed by this point anyway.  Just
    // issue a warning, do not call `itkExceptionMacro`.
    itkWarningMacro("Trying to delete object with non-zero reference count.");
  }
}

I have the warning at one point, seems to be harmless, Valgrind doesn’t detect leak at this point, so far nothing happens. Probably it is my mistake somewhere, not sure. I shall look again little later.

Edit:
Also see this post. There is a minimal example.

1 Like

Probably it is my mistake somewhere, not sure. I shall look again little later.

I have found my mistake. I used itk::MapContainer on a stack.

#include <itkMapContainer.h>
int main(int, char**)
{
	itk::MapContainer<int, int> map;
	return 0;
}
r@deb2:~/tmp/test5/build$ ./test 
WARNING: In /home/r/itk/ITK/Modules/Core/Common/src/itkLightObject.cxx, line 182
LightObject (0x7ffc902d3020): Trying to delete object with non-zero reference count.

It should be:

#include <itkMapContainer.h>
int main(int, char**)
{
	itk::MapContainer<int, int>::Pointer map = itk::MapContainer<int, int>::New();
	return 0;
}
r@deb2:~/tmp/test5/build$ ./test 
r@deb2:~/tmp/test5/build$
2 Likes

thank you,I resolved an error that is the same as yours, but I still have a warning, and when I debug a breakpoint, the system already prints that warning the first time I enter the destructor.

@Niels_Dekker Is this a bug? I thought we had a mechanism to prevent these object from being constructed on the stack?

There is a mechanism via a macro which is usually applied to filters. Maybe it was forgotten for MapContainer?

1 Like

Apparently the MapContainer() default-constructor was originally declared protected:

It was then afterwards declared public instead, on November 30, 2001, commit ENH:Unified documentation style. · InsightSoftwareConsortium/ITK@e9c0020 · GitHub
Here:
ITK/itkMapContainer.h at e9c002026368eee503bc39d363b9c9344d587385 · InsightSoftwareConsortium/ITK · GitHub

HTH, Niels

Since it has a New macro and Pointer type, it should probably use constructor disallow macro. Anyone willing to submit a PR?