0

I would like to program something that helps me to free memory automatically as soon as a pointer to an dynamically allocated address space leaves the stack. An example would be:

procedure FillMemory (var mypointer);
begin
  // CopyMemory, Move, etc... with data
end;

procedure MyProcedure;
var
  MyPointer : Pointer;
begin
  MyPointer := VirtualAlloc (NIL, 1024, MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE);
  FillMemory (MyPointer);
  VirtualFree(MyPointer, 0, MEM_RELEASE); // I would like to avoid this...
end;

I could use strings but I would also like to avoid them (which I'm not so sure if Strings in the stack get freed anyway...) Any ideas?

20
  • 3
    strings aren't in the stack. They are a reference counted pointer to the heap.
    – Gerry Coll
    Jul 15, 2013 at 11:15
  • 2
    By the reference counting mechanism - once it is zero, the memory is released. This is managed by the compiler for strings and dynamic arrays. A possible solution to your question would be to use a dynamic array of byte, in later (2009+?) Delphi versions this is predefined as TBytes (docwiki.embarcadero.com/Libraries/XE4/en/System.SysUtils.TBytes)
    – Gerry Coll
    Jul 15, 2013 at 11:21
  • 1
    @BenjaminWeiss - I believe it is the compiler that creates the necessary code. If you're trying to do what I think you are trying to do, you would need to modify the compiler. Without adding some type of reference counting, however, this could be a rather dangerous 'feature' - how would the compiler know, for example, if by the end of the method your pointer still pointed to the allocated memory or if it pointed to something it shouldn't free at all?
    – J...
    Jul 15, 2013 at 11:22
  • 1
    Do you want to make a Garbage Collector for Delphi?
    – Pieter B
    Jul 15, 2013 at 11:30
  • 2
    interface references like TInterfacedObject, IUnknown and such. RAII pattern, yes ? look at pastebin.com/YFkSNn7M Jul 15, 2013 at 11:31

2 Answers 2

4

To expand on my comments and discussion with Arioch,

If you just want a raw memory block, use a dynamic array of byte. The compiler will generate code to release this memory at the end of the method:

type
  TBytes = array of Byte; // omit for newer Delphi versions

procedure FillMemory(var Bytes: TBytes);
begin
  { passing in here will increase the reference count to 2 }
  // CopyMemory, Move, etc... with data
end; // then drop back to 1

procedure MyProcedure;
var
  Buffer : TBytes;
begin
  SetLength(Buffer, 1024);  // buffer has reference count of 1
  FillMemory (Buffer);
end;   // reference count will drop to 0, and Delphi will free memory here

Hope this all makes sense. It is midnight here, so I'm not feeling the most awake...

8
  • 3
    +1 This is what the OP wanted: automatic allocation of raw memory, with auto-release when code is out of scope. Good idea to speak about reference count - but with var it won't increase the reference count, AFAIK! :) Reference count is increased if no var nor const is used, just raw parameter. To be corrected, please. I also corrected a small typo with TBytes = array of Byte for a type definition. Jul 15, 2013 at 12:47
  • 1
    @ArnaudBouchez Is it? The question calls VirtualAlloc with PAGE_EXECUTE_READWRITE. Jul 15, 2013 at 12:49
  • 1
    @DavidHeffernan I did not see the PAGE_EXECUTE_READWRITE, you are right. But I suspect that the OP does not need it, unless he knows how to generated asm stubs on the fly, which I doubt given his question. He wrote that he "bypassed the RTL", which is a non sense - and in this case, your class-based approach won't work either. :) Jul 15, 2013 at 12:50
  • 1
    @ArnaudBouchez Maybe. I was taking the question at face value. Plus Benjamin has asked lots of VirtualAlloc questions before. Nothing in the question talks about bypassing RTL. I'm not sure where that comes from. In any case, you don't need the RTL to make classes, not for classes that implement interfaces, not for automatic reference counting of interfaces. Jul 15, 2013 at 12:53
  • 1
    @DavidHeffernan so you don't consider the IMPLEMENTAION of TObject and TIniterfacedObject part of RTL ??? Jul 15, 2013 at 14:45
3

Managed types have their references counted and when the count drops to zero, they are finalized. If you have a local variable, then when it goes out of scope, its reference count will drop to zero.

So, you can create a descendent of TInterfacedObject which you refer to using an interface. Something like this:

type
  TLifetimeWatcher = class(TInterfacedObject)
  private
    FDestroyProc: TProc;
  public
    constructor Create(const DestroyProc: TProc);
    destructor Destroy; override;
  end;

constructor TLifetimeWatcher.Create(const DestroyProc: TProc);
begin
  inherited Create;
  FDestroyProc := DestroyProc;
end;

destructor TLifetimeWatcher.Destroy;
begin
  if Assigned(FDestroyProc) then
    FDestroyProc();
  inherited;
end;

You can then use it like this:

procedure MyProcedure;
var
  MyPointer: Pointer;
  LifetimeWatcher: IInterface;
begin
  MyPointer := VirtualAlloc (NIL, 1024, MEM_COMMIT or MEM_RESERVE, 
    PAGE_EXECUTE_READWRITE);
  LifetimeWatcher := TLifetimeWatcher.Create(
    procedure
    begin
      VirtualFree(MyPointer, 0, MEM_RELEASE);
    end;
  )
  FillMemory(MyPointer);
end;

When LifetimeWatcher leaves scope, the implementing object is destroyed and the procedure that you passed to TLifetimeWatcher.Create is executed.

It would be easy enough to specialise this idea to be dedicated to your use case. And that would make the code at the call site more concise.

That would look like this:

function VirtualAllocAutoRelease(Size: SIZE_T; Protect: DWORD;
  out LifetimeCookie: IInterface): Pointer;
var
  Ptr: Pointer;
begin
  Ptr := VirtualAlloc(nil, Size, MEM_COMMIT or MEM_RESERVE, Protect);
  Win32Check(Ptr<>nil);
  LifetimeCookie := TLifetimeWatcher.Create(
    procedure
    begin
      VirtualFree(Ptr, 0, MEM_RELEASE);
    end
  );
  Result := Ptr;
end;

And you'd use it like this:

procedure MyProcedure;
var
  MyPointer: Pointer;
  LifetimeWatcher: IInterface;
begin
  MyPointer := VirtualAllocAutoRelease(1024, PAGE_EXECUTE_READWRITE, 
    LifetimeWatcher);
  FillMemory(MyPointer);
end;
6
  • 1
    The OP want to bypass the whole getmem process (see his comment). So using a class is not possible for him. :) All this sounds a bit confused... but your answer is perfectly valid (even if I doubt he is using a version of Delphi handling delegates). Jul 15, 2013 at 12:54
  • 1
    @ArnaudBouchez Nothing in the question indicates that classes are not viable. One of his recent questions is tagged XE4, but in any case, why should we be tethered to Delphi 7! Jul 15, 2013 at 12:55
  • 1
    @ArnaudBouchez though i cannot see much practical sense i nthis, but hwy cannot you make a single-purpose IInterface-implementing class that does work without using heap manager ? Yes, you would have to override .NewInstance and so one - but that IS possible, isn't it ? Again, i do not talk about practical profit from this, only about your "not possible" Jul 15, 2013 at 14:48
  • This answer is a good alternative and even considers the PAGE_EXECUTE_READWRITE +1
    – Ben
    Jul 15, 2013 at 16:20
  • @Arioch'The Sounds like Frankenstein coding to me. And as for the question, the OP wanted to bypass the whole getmem process, so, unless NewInstance is overriden, using a class is just not a solution to his concern.... but how may we find a good solution to a biased question? Aug 6, 2013 at 6:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.