memset
fills a number of bytes with the specified value. In Delphi, we use FillChar
for this. But if the value we want to fill with is zero, you can also use the ZeroMemory
function.
memcpy
copies a block of bytes from one location to another (in RAM). In Delphi, we use Move
for this. You can also use CopyMemory
(or the identical function MoveMemory
) if you want to work with pointers instead of Delphi variables.
That is,
Move(a, b, n)
copies n bytes from the data named a to the location of b, where a and b are variables. This is equivalent to
CopyMemory(@b, @a, n)
where @a and @b are the pointers to the source and destination, respectively. (Personally, I think the latter syntax is easier to explain, in some sense. It takes two addresses, and after all, that is how we work with memory.)
Hence, if p
and q
are pointers, you can do
CopyMemory(q, p, n)
or
Move(p^, q^, n).
You might also want to know how to allocate, reallocate, and free memory on the heap in Delphi. You use the GetMem
, ReallocMem
, and FreeMem
procedures, respectively.
Working with pointers
Deplhi can be rather restrictive when it comes to pointer arithmetics. But on a 32-bit system (such as the ones running Delphi applications), a pointer is really just a 32-bit unsigned integer, that is, a cardinal
. So you can work with pointers just like cardinals, if you just tell the compiler to do so.
Hence, if the compiler doesn't allow
myPtr + 200
then you can do
cardinal(myPtr) + 200.