[DUG] StrCopy problem - Reason : Const value not allowed to be changed

Jianming Lin (FMI) jianmingl at fmi.co.nz
Mon May 13 10:35:03 NZST 2013


It seems that we all focus on the StrCopy. That's misleading.

 

Let's look at this code:

 

procedure test;

var  a: pChar;

begin

   a := 'abc';

   a[1] := 'A';

end;

 

 

procedure TForm1.Button1Click(Sender: TObject);

begin

  test;

end;

 

The line : a[1] will cause exactly same AV as your example.

 

As CPU window shows cpu instruction in assembly language, not many
people can understand it, I do further experiment:

 

 

 

procedure test;

var  a: pChar;

const ConsStr  = 'abc';

begin

   a := @ConsStr[1];

   a[1] := 'A';

end;

 

 

The same AV will happen. And that's the key problem where your code
actually is.

 

Now we can see that the reason of your code crash:

 

Delphi compile 'abcdefghi' as the local const value. 

Certainly constant value is not allowed to change.

If you put a line : ConsStr := 'def'; Compiler won't let you go.

If you purposely use the trick of pointer : 

   a := @ConsStr[1];

   a[1] := 'A';

to bypass compiler checking, the  operating system then has to activate
the last protection by showing the AV and stop your program to run. 

 

 

Bevan is right : the area of memory for const value is protected while
the application is running.

 

 

 

 

________________________________

From: delphi-bounces at listserver.123.net.nz
[mailto:delphi-bounces at listserver.123.net.nz] On Behalf Of Ross Levis
Sent: Sunday, 12 May 2013 2:39 a.m.
To: 'NZ Borland Developers Group - Delphi List'
Subject: [DUG] StrCopy problem

 

var

  a: pChar;

  b: pChar;

begin

  a := 'abcdefghi';

  b := 'jklmnopqr';

  StrCopy(a,b);

end;

 

Question:  Why does this code crash?

 


##################################################################################################
Attention: 
This mail and any attachments are for the use of the intended recipient only, and may contain
information which is confidential and/or privileged.  If you have received this email in error,
please advise us by return email and immediately delete this email together with all attachments.
The contents of this email may only be used, distributed or copied with the consent of the author. 

Fairview Metal Industries Ltd takes reasonable precautions to minimise the risk of this email containing
any viruses but does not accept liability for any damage caused by software viruses and advises 
the recipient to carry out their own virus check on any attachments.

##################################################################################################
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://listserver.123.net.nz/pipermail/delphi/attachments/20130513/8071fb53/attachment-0001.html 


More information about the Delphi mailing list