Mad Scientist
Mad Scientist

Reputation: 331

Casting literals to PChar / PAnsiChar

I've got really stupid question... Why this code:

PChar('x');

causes "Access violation" error? Compiler optimalisation?

Example:

var s: String;
...
s := StrPas(PAnsiChar('x'));

This causes AV in Delphi 5 / Delphi XE

Or this one:

Windows.MessageBox(0, PChar('x'), PChar('y'), 0);

This causes AV in Delphi 5, but not in Delphi XE In XE there is an empty MessageBox

Console example:

program Project1;
{$APPTYPE CONSOLE}
uses
  SysUtils, Windows;
var s: String;
begin
  s := StrPas(PChar('xxx'));   // EAccessViolation here
end.

Upvotes: 2

Views: 1096

Answers (1)

David Heffernan
David Heffernan

Reputation: 612794

StrPas(PAnsiChar('x'));

I posit that 'x' is treated as a character literal rather than a string literal. And so the cast is not valid. If so then this will work as you would expect

StrPas('x');

due to an implicit conversion. Or

StrPas(PAnsiChar(AnsiString('x')));

thanks to the explicit conversion.

I think the former is probably to be preferred. Literals don't need casting to null terminated pointer types. The compiler can emit the correct code without the cast. And casts always run the risk of suppressing an error.

Upvotes: 4

Related Questions