[lazarus] Lazarus ansistring AV?

Marco van de Voort marcov at stack.nl
Fri Jul 25 18:12:07 EDT 2003


> At 23:53 25-7-2003 +0200, Marco van de Voort wrote:

> >First, because of the construct with the pointer and the @ in the WITH
> >clause, newtext isn't initialised to zero (as ansistrings should)
> >
> >The declaration of LMessage should do that, but "TLMessage" doesn't contain
> >the ansistring field, so it is not initialised to zero. When nextext is
> >used, it is decreased in ref count, and since the random value points into
> >deep space, so accessing the ref count via the pointer can produce an AV.
> >
> >It can be remedied by initing newtest to zero:
> >
> >integer(newtext):=0;            // pchar(newtext):=nil isn't allowed.
> 
> Why isnt the LMessage declared as TLMInsertText anyway ?

It seems to depend on a CASE statement if the base type is used.

That is also dangerous if TLMInsertText is larger than LMessage (and it is),
and field beyond the range defined by LMessage are used.
 
> But keep the lifetime of the string in mind. Cast a string to a PChar and 
> post it as a message will never ever work and allways lead to the most 
> unpredictable and hard to trace errors.

It is one of the problems of Pascal (at least Borland dialects), that
conversion and cast are noted the same. Please keep in mind that they are
NOT the same, specially in the case of automated types.

What's the difference?
- a typecast is like changing typing for a memory location. 
- a conversion truely converts a type from one to another.


A pchar to ansistring is a conversion (the data needed for automising the
type needs to be added). However this is an conversion

var p:pchar;
    s:ansistring;

s:=p;

And this is not:

s:=string(p);

(one of the errors in the original snippet)

The other way around (pchartyped:=ansistringtyped) isn't  allowed as conversion,
only as cast.

pchartyped:=pchar(ansistringtyped);

This construct is also somewhat dangerous. 

The pchar becomes a reference to the content of the ansistring. The
ansistring will still disappear when it goes out of scope. 
(and pchar will remain pointing to released memory)
Any modification to the pchar will affect the ansistring.







More information about the Lazarus mailing list