开发者

Delphi - ADO query and FillChar generates errors

I have the following code:

var wqry:TAdoQuery;
...
  FillChar(wSpaces,cSpacesAfter,' ');
  try
    wqry := TADOQuery.Create(nil);//here the error
    wqry.Connection:=...

cSpacesAfter is a constant and has the value 1035. wSpaces is a local string variable. The problem is that I receive the following error when TAdoQuery is created

Delphi - ADO query and FillChar generates errors

even it is in french, I believe you got the idea.....

If I comment the FillChar code, everything works ok. I have the usual compiler directives, nothing special. I'm using Delphi 7.

Can someone tell me what is wrong w开发者_如何学JAVAith that code?


The troublesome code is most likely this one

FillChar(wSpaces,cSpacesAfter,' ');

I'm assuming that wSpaces is of string type. A string variable is in fact nothing more than a pointer to the data structure that holds the string. You don't need to use pointer syntax because the compiler takes care of that for you.

So what this code does is overwrite the variable holding that pointer with 4 space characters and then write 1031 more spaces over the top of whatever follows the variable. In short you will completely corrupt your memory. That would explain why the FillChar works but the very next line of code dies a painful and dramatic death.

If your string indeed had space for 1035 characters your could instead write:

FillChar(wSpaces[1], cSpacesAfter, ' ');

However, if may be more idiomatic to write:

wSpaces := StringOfChar(' ', cSpacesAfter);


FillChar procedure fills out a section of storage Buffer with the same byte or character FillValue FillCount times.

It is principally used to initialise arrays of numbers. It can be used to initialise records and strings, but care should be used to avoid overwriting length fields. StringOfChar is best for filling out strings to the same character.

Are you sure wSpaces has the size enough to fit all of cSpacesAfter you write to it?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜