strange behaviour

From: Nicolai Hansen (nic_at_aub.dk)
Date: 10/24/03


Date: 24 Oct 2003 00:51:26 -0700

Hi guys,

In an application I need to get the folder in which Windows are
installed.

My first attempt was:

var
 p: PChar;
 s: String;
begin
 GetWindowsDirectory(p, 256);
 s:=p;
 Showmessage(s); <---
 Showmessage('done');
end;

which crashed on the marked line (need to say that both s and p got
the right values, c:\winnt)

Second attempt:

var
 p: PChar;
 s: String;
begin
 GetWindowsDirectory(p, 256);
 s:=p;
 Showmessage('done'); <---
end;

weird.. Third attempt:

var
 p: PChar;
 s: String;
begin
 new(p);
 GetWindowsDirectory(p, 256);
 s:=p;
 Showmessage('done');
 dispose(p);
end;

which works! I thought, 'great!' and did:

var
 p: PChar;
 s: String;
begin
 new(p);
 GetWindowsDirectory(p, 256);
 s:=p;
 Showmessage(s); <---
 Showmessage('done');
 dispose(p);
end;

Crash again. I then tried

var
 p: PChar;
 s: String;
 i: Integer;
begin
 i:=GetWindowsDirectory(p, 256);
 s:=copy(p, 1, i);
 Showmessage(s); <---
 Showmessage('done');
end;

but nope. I changed it back to the working, with a little
modification:

var
 p: PChar;
 s: String;
begin
 new(p);
 GetWindowsDirectory(p, 256);
 s:=p;
 dispose(p);
 Showmessage('done'); <---
end;

In the end I made it work by declaring the pchar global and
new/dispose in oncreate/ondestroy. But why, oh why, does it behave
like this?

/Nic



Relevant Pages

  • Re: Strings
    ... Windows defaults to using 4096 as the buffer size for COM ports - I ... function ReadStringFromFile(const fileName: string): string; ...
    (borland.public.delphi.thirdpartytools.general)
  • Re: in PChar schreiben
    ... > ich habe gerade ein Brett .. ... > p: PChar; ... > s: String; ...
    (de.comp.lang.delphi.misc)
  • Re: var p: PChar -> p not treated the same as p[0] by the compiler
    ... but now I understand that for Delphi, a PChar ... thinking of a PChar var as ... a string is *not* good. ... Note that for future programming there are AnsiChar, ...
    (borland.public.delphi.language.basm)
  • Re: Help on speed up a "string normalizer"
    ... function Normalize(const InStr: string): string; ... c1, c2: PChar; ...
    (borland.public.delphi.language.basm)
  • Re: StringList with spaces and quotes in name-values?
    ... function ParamToList(Param: String): TStringList; ... If anyone has recommendations for speedier code (would using PChar be ...
    (borland.public.delphi.language.objectpascal)