title: Delphi7, passing object's interface - causes Invalid Pointer Operation when freeing the object
body: <p>I have a class that implements an interface, which is made available for plugins.
  The declaration of class is quite simple. There is only one instance of this class for an entire application. When the function that returns the interface is called, it calls _AddRef on the retrieved interface before passing it back as result. Unfortunately it works until I try to free the object (see "finalization" section) - it reports Invalid Pointer Operation. If I comment it out, it works fine (however FastMM reports memory leaks, so the object is not being freed).</p>
  
  <p>Here is the part of the code in the function that returns the interface (in fact it is an overridden QueryInterface of my "ServicesManager" class).</p>
  
  <pre><code>if ConfigManager.GetInterface(IID, obj) then
  begin
    ISDK_ConfigManager(obj)._AddRef;
    result:= 0;
  end
  </code></pre>
  
  <p>and the code of ConfigManager class ...</p>
  
  <pre><code>type
    TConfigManager = class(TInterfacedObject, ISDK_ConfigManager)
    private
    ... 
    end;
  
  var
    ConfigManager: TConfigManager;
  implementation
  
  ...
  
  initialization
    ConfigManager:= TConfigManager.Create();
  finalization
    if ConfigManager &lt;&gt; nil then
      FreeAndNil(ConfigManager); //if I comment it out, it leaks the memory but no Invalid Ptr. Op. raises
  </code></pre>
  
  <p>What am I doing wrong?
  I need to pass a reference to exactly <em>this</em> instance of ConfigManager.</p>