Memory Management 4

Source: Internet
Author: User

An example of using a private heap: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
{Create heap}
Myheap: = heapcreate (heap_zero_memory, 1024*1024*2, 0); {create a 2 m 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 with an error}
{Get memory block size}
Num: = heapsize (myheap, 0, P );
{Assign values to each byte of the 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 memory block content and size}
Showmessagefmt ('% s, % d', [STR, num]); {abcdefg, 7}
//////////////////////////////////////// /////////////
{Memory expansion, this is a different sentence. The above code is repeated below}
P: = heaprealloc (myheap, 0, P, 26 );
If P = nil then exit; {exit with an error}
{Get memory block size}
Num: = heapsize (myheap, 0, P );
{Assign values to each byte of the 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 memory block content and size}
Showmessagefmt ('% s, % d', [STR, num]); {abcdefghijklmnopqrstuvwxyz, 26}
//////////////////////////////////////// /////////////
{Release memory}
Heapfree (myheap, 0, P );
{Destroy heap}
Heapdestroy (myheap );
End;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.