[fpc-devel] Access Violation with nested DLL's compiled by FPC(and some more info on bug #4538)

L505 fpc505 at z505.com
Sat Dec 10 09:33:55 CET 2005


> >> Before we can say something, what functions do you call, what  params,
> >> what calling convention etc.
> >> Does it happen in one specific sequence of calls, to specific
> >> functions/methods etc.
> >>
> >> Please provide some more info.
> >
> >
> > http://www.freepascal.org/bugs/showsource.php3?ID=4538
>
> Whoops, I didn't saw that there was a bugrep.
>
> I'm not shure if FPC behaves the same as Delphi, but I think it does.
>
> In Delphi you cannot exchange ansistrings between dlls, unless you have
> a shared memory manager. Normally each exe (or dll) has its own memory
> manager. So when you pass a string to a dll and it it goes out of scope
> there (since it is changed) it is released there. So a allocated memory
> block from one manager is freed in another. This gives all kinds of
> unexpected errors at strange places.
>
> IIRC the way constant strings are allocates it changed, so that may be
> the reason that you didn't see the error on dlls generated by an older fpc.
>
> Marc
>

To the original person who posed the bug report:
As Marc stated.. it is definitely a bad idea to use an ansistring as a function
result in DLL's - unless it was a BPL or you were using shared memory.

Did you include the sharemem unit in the delphi program maybe, which caused it to
work there just fine but not in FPC?  If not, how long was the program tested and how
many users actually used the program without problems? Sometimes you can get away
with strings temporarily, but the bugs pop up later or in random occurrences.

The general safe rule is to never return a string into a function result when passing
it to a DLL without shared memory. There are ways to use ansistrings without shared
memory, such as using setlength calls in certain places, and taking extra caution
(like using CONST parameters in some cases).. but I've learned that it takes extra
brain effort to try and trick/escape the reference counter, so using pchars makes you
extra safe. That is, assuming you study pchars thoroughly (and there are a lot of
incorrect information out there so a book needs to be written on pchars).

The other problem with trying to escape/trick the reference counter is you take extra
CPU power to do it. The real disadvantage is not the extra cpu that it could cost,
but the maintainability. Eventually your tricks catch up with you and you make a
small mistake when trying to trick the reference counter. Whereas if you go in
knowing what memory you are allocating, you can understand your mistakes and fix them
rather than try to play more tricks.


--
L505




More information about the fpc-devel mailing list