[fpc-pascal] Stack corruption setting UnicodeString Char
Mattias Gaertner
nc-gaertnma at netcologne.de
Wed Oct 19 10:11:17 CEST 2011
Felipe Monteiro de Carvalho <felipemonteiro.carvalho at gmail.com> hat am 19.
Oktober 2011 um 09:13 geschrieben:
> Hello,
>
> Usually when we work with PChars we do things like this to set the
> final terminator:
>
> var
> ansistr: ansistring;
> begin
> // Copy the originating string taking into account the specified length
> SetLength(ansistr, len+1);
> System.Move(source^, ansistr[1], len);
> ansistr[len+1] := #0;
> SetLength(ansistr, len);
>
> And it works fine. You get a string with correct length and a final #0
> terminator.
I never saw such code for ansistring. Only for shortstring.
SetLength(ansistring) already allocates memory for the header+len+1, creates the
header and sets the len+1 character to #0.
Simply do:
SetLength(ansistr, len);
if len>1 then
System.Move(source^, ansistr[1], len);
>
> Now, I simply tryed the same code for a unicodestring, and it corrupts my
> stack:
>
> procedure Unicode2AnsiMove(source:pwidechar;var dest:ansistring;len:SizeInt);
> var
> widestr: unicodestring;
> begin
> {$ifdef PASWSTRING_VERBOSE}WriteLn('Unicode2AnsiMove START');{$endif}
> // Copy the originating string taking into account the specified length
> SetLength(widestr, len+1);
> System.Move(source^, widestr[1], len*2);
> PWideChar(@widestr)[len] := #0; // <--- This corrupts the stack
This would corrupt the stack for ansistring too. This would only work for
shortstring.
widestr is a unicodestring is a pointer to widechar.
PWideChar(widestr)[len] := #0;
> SetLength(widestr, len);>
> I already fixed the problem by simply not setting this last widechar
> to #0, but now I got puzzled: Any ideas why this doesn't work?
>
> It crashes only a bit after this procedure, but I found that this was
> the statement which caused the problem.
Mattias
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20111019/9100012b/attachment.html>
More information about the fpc-pascal
mailing list