delphi invalid pointer operation

Viewed 4297

Here I have a few lines of delphi code running in delphi 7:

    var
      ptr:Pointer ;
    begin
      ptr:=AllocMem(40);
      ptr:=Pchar('OneNationUnderGod');
      if ptr<>nil then
        FreeMem(ptr);
    end;

Upon running this code snippet, FreeMem(ptr)will raise an error:'invalid pointer operation'. If I delete the sentence:

     ptr:=Pchar('OneNationUnderGod');

then no error will occur. Now I have two questions,

1.Why is this happening? 2. If I have to use the Pchar sentence, how should I free the memory allocated earlier?

Much appreciation for your help!

3 Answers
Related