Memory management in Delphi[4]
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 =class (TForm) Button1: TButton; procedure Button1Click (Sender: TObject); end ; var Form1: TForm1; implementation {$ R * .dfm} var MyHeap: THandle; {heap handle} p: Pointer; procedure TForm1.Button1Click (Sender: TObject); var i, num: Integer; p2: Pointer; str: string ; begin {build heap} MyHeap: = HeapCreate (HEAP_ZERO_MEMORY, 1024*1024*2, 0); {Build a 2M heap} if Myheap =0 then Exit; { Exit if creation fails} {Allocate memory from the heap} p: = HeapAlloc (MyHeap, 0, 7); if p =nil then Exit; {exit on error} {Get memory block size} num: = HeapSize (MyHeap, 0, p); {Assign a value to each byte of a memory block} p2: = p; for i: =0 to num-1 do begin Byte (p2 ^): = i +65; p2: = Ptr (Integer (p2) + 1); end ; {Value} p2: = p; str: = ''; for i: =0 to num-1 do begin str: = str + Chr (Byte (p2 ^)); p2: = Ptr (Integer (p2) + 1); end ; {Display the content and size of the memory block} ShowMessageFmt ('% s,% d', [str, num]); {ABCDEFG, 7} ///////////////////////////////////////////////////////// /// {Expand memory, only this sentence is different, the following are repeated the above code} p: = HeapReAlloc (MyHeap, 0, p, 26); if p =nil then Exit; {exit on error} {Get memory block size} num: = HeapSize (MyHeap, 0, p); {Assign a value to each byte of a memory block} p2: = p; for i: =0 to num-1 do begin Byte (p2 ^): = i +65; p2: = Ptr (Integer (p2) + 1); end ; {Value} p2: = p; str: = ''; for i: =0 to num-1 do begin str: = str + Chr (Byte (p2 ^)); p2: = Ptr (Integer (p2) + 1); end ; {Display the content and size of the memory block} ShowMessageFmt ('% s,% d', [str, num]); {ABCDEFGHIJKLMNOPQRSTUVWXYZ, 26} ///////////////////////////////////////////////////////// /// {Free up memory} HeapFree (MyHeap, 0, p); {Destroy heap} HeapDestroy (MyHeap); end ; end .