The Problem with PChar

This use of PChar was so handy that this type was often used instead of other pointers, like PInteger in the following code fragment. The code below, extracted from the PointerMath example, reads an array using a pointer (a PChar pointer) and moving the pointer from one Integer to the next by adding 4 to it (since an Integer is four bytes). Here is the complete code of the method:

procedure TFormPointerMath.Button1Click(Sender: TObject); var

TenIntegers: array [1..10] of Integer; pOneInteger: PChar; I: Integer; begi n

// now read using a pointer pOneInteger := ©TenIntegers; for I := 1 to 10 do begi n

Memo1.Lines.Add(

'Address: ' + IntToHex (Integer(pOneInteger), 8) + ' - Value: ' + IntToStr (PInteger(pOneInteger)A)); pOneInteger := pOneInteger + 4; end; end;

If you compile this code in any version of Delphi from Delphi 2 to Delphi 2007, you'll get an output like the following:

Address:

0012F4A8

- Value:

1

Address:

0012F4AC

- Value:

2

Address:

0012F4B0

- Value:

3

Address:

0012F4B4

- Value:

4

Address:

0012F4B8

- Value:

5

Address:

0012F4BC

- Value:

Address: 0012F4C4

Address: 0012F4C8

Address: 0012F4CC

Value: 7

Value: 8

Value: 9

Value: 10

You can see that the address is increased by 4 every time, and the proper value is returned. I have to underline it, because if you now recompile the same exact code in Delphi 2009, you'll get totally different output:

Address: Address: Address: Address: Address: Address: Address: Address: Address: Address:

0012F4AC 0012F4B4 0012F4BC 0012F4C4 0012F4CC 0012F4D4 0012F4DC 0012F4E4 0012F4EC 0012F4F4

Value: 1

Value: 3

Value: 5

Value: 7

Value: 9

Value: 29043072

Value: 4476177

Value: 4400843

Value: 4403501

Value: 4474789

This is not what the code meant, of course, but it is what the code says. Incrementing the pointer by 4 characters in Delphi 2009 means moving 8 bytes ahead, since each character is now two bytes. Not only the output is wrong, but we are also doing an illegal memory access, that could be very dangerous in cases where we were writing to that memory area.

Was this article helpful?

0 0
Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook


Post a comment