Question

Delphi 2009 - AnsiStrings + ShortString

Asked by: ThievingSix

Ok, so I'm getting very frustrated with something that should be simple. Combining an AnsiString and a ShortString. Sounds simple?

Let's start with the short string definition:

  TFileRecord = record
    MurmurHash,
    AbsolutePosition,
    UncompressedSize,
    CompressedSize: DWORD;
    CompressionType: TCompressionType;
    Path: String[255];
  end;

Now let's see the application:

var
  SelData : TFileRecord;
  OutputFolder : AnsiString;
  OutputFile : AnsiString;
begin
  OutputFolder := 'C:\Users\Administrator\Desktop\EFSoW\MRS Examples\Test Output\';
  SelData := PFileRecord(lvFileList.Items[I].Data)^;
  OutputFile := OutputFolder + SelData.Path;

Now I can debug and step through the code and check that SelData.Path is not corrupted when the error occurs. The above is in a loop. When that loop hits a certain file from the ListView(It's always the same file), it gives me a nice AV which looks like this:

Access violation at address 00401B1D in module '*****_Archive_Creator.exe'. Read of address 00007FFC.

Then when trying to exit the application I get about a half a dozen more. So I'm assuming that memory is getting modified when it shouldn't. But how? Also TFileRecord.Path used to be an Array[0..255] Of Char, had to move it to Ansi for better speed. Like I said I can walk through the code when it hits that certain file and can see it's not corrupted.

Update: Just went even further into the code, seems that when it tries to allocate a new string the call fails on GetMem. Not sure if that's any further help.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-08-20 at 04:33:58ID24667724
Topic

Delphi Programming

Participating Experts
1
Points
500
Comments
8

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Convert TString to AnsiString
    Hi. I have a question about Borland C++. I have Delphi too, and there I can do this Edit1.Text := ListBox.Items[3]; but when I do the same thing in C++ Edit1.Text = ListBox.Items[3]; I get the error "Can't convert from TString to AnsiString". I have tried to c...
  2. AnsiString of C++Builder
    I am asking this question here as there is no C++Builder specific area. I mostly program with Delphi now but have to fall back to C++ for a project. Hence, the question. I very much like the "string" data type of Pascal which is very convenient to use everywhere, e...
  3. writing AnsiString to file in buiilder
    how do i write an ansistring (from an editbox for example) into a file?
  4. AnsiString to char
    Hi, How can I transform AnsiString to char with the BCB6? Thanks, Ronald
  5. Help with AnsiString to char* conversion
    HI everyone, im new to C++ ive been programming in delphi for about 4 years now and decided to write my next project in C++. But i have a problem, i want to convert an AnsiString to char* yeah there are lots of examples for this but i keep getting an "/x18" at the ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: den4bPosted on 2009-08-20 at 04:47:51ID: 25141235

I had a similar problem, and I discovered an elegant solution for using Unicode strings in records. You can use this new ShortUnicodeString type in records instead of ShortString, and use it in assignments with normal strings (seamlessly). For this I used new feature in Delphi 2009, so it is not going to work in earlier versions.


unit Unit2;
 
interface
 
type
  ShortUnicodeString = record
  private
    Data: array [0..255] of Char;
  public
    class operator Implicit(const S: ShortUnicodeString): String; inline;
    class operator Implicit(const S: String): ShortUnicodeString; inline;
  end;
 
type
  TestRec = record
    Name: ShortUnicodeString;
    Int: Integer;
  end;
 
implementation
 
uses
  SysUtils;
 
class operator ShortUnicodeString.Implicit(const S: ShortUnicodeString): String;
begin
  Result := StrPas(S.Data);
end;
 
class operator ShortUnicodeString.Implicit(const S: String): ShortUnicodeString;
begin
  // NOTE: Longer strings are silently truncated!
  StrPLCopy(Result.Data, S, Length(Result.Data)-1);
end;
 
end.

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:

Select allOpen in new window

 

by: ThievingSixPosted on 2009-08-20 at 05:07:26ID: 25141387

The problem is that I can't use unicode. Reason being is that the end result is an archive with 3000+ files in it. This data is fed to another application that uses it for Ansi Win32 API calls so I would have to do the conversion to ansi anyway. I'd rather spend more time converting while compiling then while decompiling.

 

by: den4bPosted on 2009-08-20 at 05:53:07ID: 25141815

Here are some ideas for your access violation:

* You used "I" index in lvFileList.Items[I].Data)^, by I dont even see it being declared as a variable. Make sure you check that "I" does not go outside of the boundaries of array, e.g. I >= 0 and I < lvFileList.Items.Count.

* Use Assert(Assigned(lvFileList.Items[I].Data)) before referencing that pointer, it might be nil for some elements, causing that AV

* You are probably freeing that Data when you deallocate the nodes, which might explain loads of AV when you exit the app. Check that TListItem or TListView are not trying to free your Data as well as you.

* Check all allocation and deallocation, i.e. GetMem, FreeMem, etc - make sure they are synchronized, and make sure you set all pointers to NIL once you free them, so nothing else will try to free them again.

It is hard (or impossible) to find a source of Access Violation with this tiny snippet of code, especially when all allocation and deallocation routines are not a part of this snippet.

 

by: ThievingSixPosted on 2009-08-20 at 06:05:16ID: 25141956

The code that I have shown is a cross section. The variable I is defined in a for loop. The data is checked for being nil. And the loads of AV's while closing the application only occur after the first AV shown in the first post.

I can post the functions in a sec. I'd also like to point out that the error only occurs when there is no compression done to the file. You'll understand more when I post the code.

 

by: ThievingSixPosted on 2009-08-20 at 06:18:20ID: 25142113

Below is all the code in question. And for some reason this line:

BufferOut := AllocMem(BufferSize);

Changed to this line:

BufferOut := AllocMem(BufferSize + 3);

Makes everything work.

How in the world would that, especially when you follow the code to see how it is used, make combining two strings fail!?

procedure TfrmMain.btnExtractAllClick(Sender: TObject);
var
  SelData : TFileRecord;
  Data : Pointer;
  I : Integer;
  OutputFolder : AnsiString;
  OutputFile : AnsiString;
  Msg : TMsg;
begin
  If lvFileList.Items.Count = 0 Then Exit;
  //If Not(SelectDirectory('Select Output Folder','',OutputFolder)) Then Exit;
  OutputFolder := 'C:\Users\Administrator\Desktop\EFSoW\MRS Examples\Test Output\';
  pbDecompile.Min := 1;
  pbDecompile.Max := lvFileList.Items.Count;
  pbDecompile.Position := 1;
  For I := 0 To lvFileList.Items.Count - 1 Do
    begin
    SelData := PFileRecord(lvFileList.Items[I].Data)^;
    OutputFile := '';
    OutputFile := OutputFolder + SelData.Path;
    ForceDirectories(ExtractFilePath(String(OutputFile)));
    If ExtractFile(edArchive.Text,SelData,AES,RSASSA,Data) Then
      begin
      Try
        SaveBufferToFile(String(OutputFile),Data,SelData.UncompressedSize);
      Finally
        FreeMem(Data);
        Data := nil;
      end;
    end;
    pbDecompile.Position := I + 1;
    StatusBar.Panels[1].Text := Format('Extracting(%d/%d) - File: %s',[I + 1,lvFileList.Items.Count,SelData.Path]);
    If PeekMessage(Msg,0,0,0,PM_REMOVE) Then
      begin
      TranslateMessage(Msg);
      DispatchMessage(Msg);
    end;
  end;
  ShellExecute(0,'open',PChar(OutputFolder),'','',SW_SHOWNORMAL);
end;
 
function ExtractFile(const FileName: String; const FileData: TFileRecord; AES: TLbRijndael; RSASSA: TLbRSASSA; var Buffer: Pointer): Boolean;
var
  hFile : DWORD;
  BytesRead : DWORD;
  Header : THeader;
begin
  Result := False;
  hFile := CreateFile(PWChar(FileName),GENERIC_READ,0,nil,OPEN_EXISTING,0,0);
  If hFile = INVALID_HANDLE_VALUE Then Exit;
  Try
    Header := GetHeader(hFile);
    If (Header.Magic <> Magic) Or (Header.NumberOfRecords = 0) Then Exit;
    AES.GenerateKey(Header.Key1);
    RSASSA.PublicKey.Passphrase := Header.Key2;
    SetFilePointer(hFile,FileData.AbsolutePosition,nil,FILE_BEGIN);
    Buffer := AllocMem(FileData.CompressedSize);
    If Buffer = nil Then Exit;
    Try
      If (Not(ReadFile(hFile,Buffer^,FileData.CompressedSize,BytesRead,nil))) Or (BytesRead <> FileData.CompressedSize) Then Exit;
      If Not(DecompressDecryptToBuffer(Buffer,BytesRead,AES,RSASSA,FileData.CompressionType,FileData)) Then Exit;
    Except
      If Buffer <> nil Then FreeMem(Buffer);
    end;
    Result := True;
  Finally
    CloseHandle(hFile);
  end;
end;
 
function GetHeader(hFile: DWORD): THeader;
var
  BytesRead : DWORD;
begin
  FillChar(Result,SizeOf(THeader),0);
  If hFile = INVALID_HANDLE_VALUE Then Exit;
  SetFilePointer(hFile,-(SizeOf(THeader)),nil,FILE_END);
  ReadFile(hFile,Result,SizeOf(THeader),BytesRead,nil);
  Decrypt(@Result,SizeOf(THeader),Magic);
end;
 
function DecompressDecryptToBuffer(var BufferIn: Pointer; var BufferSize: DWORD; AES: TLbRijndael; RSASSA: TLbRSASSA; CompressionType: TCompressionType; FileRecord: TFileRecord): Boolean;
var
  DataSize : DWORD;
  BufferOut: Pointer;
begin
  Result := False;
  BufferOut := nil;
  DataSize := BufferSize;
  BufferSize := 0;
  If Not(VerifyAndDecrypt(BufferIn,DataSize,AES,RSASSA)) Then Exit;
  Try
    Case CompressionType Of
      ctNone:
        begin
        BufferSize := DataSize;
        BufferOut := AllocMem(BufferSize);
        Move(BufferIn^,BufferOut^,BufferSize);
      end;
      ctLZOX,
      ctLZOY: LZO.DecompressData(BufferIn,BufferOut,DataSize,FileRecord);
      ctUCL: UCL.DecompressData(BufferIn,BufferOut,DataSize,FileRecord);
      ctLZMA: LZMA.DecompressData(BufferIn,BufferOut,DataSize,FileRecord);
    end;
    If (DataSize = 0) Or (BufferOut = nil) Then Exit;
    If MurmurHash(BufferOut,DataSize) <> FileRecord.MurmurHash Then Exit;
    FreeMem(BufferIn);
    BufferIn := BufferOut;
    System.PByte(BufferIn)[DataSize] := 0;
    BufferSize := DataSize;
    Result := True;
  Except
    raise;
  end;
end;
 
function VerifyAndDecrypt(var Buffer: Pointer; var BufferSize: DWORD; AES: TLbRijndael; RSASSA: TLbRSASSA): Boolean;
var
  OutStream,
  KeyStream : TMemoryStream;
  KeySizes : Array[0..1] Of Byte;
  SigBuf : Array[0..127] Of Byte;
begin
  //Initialize Result
  Result := False;
  //Create streams for data
  OutStream := TMemoryStream.Create;
  KeyStream := TMemoryStream.Create;
  Try
    Move(System.PByte(Buffer)[BufferSize - SizeOf(KeySizes)],KeySizes[0],SizeOf(KeySizes));
    //Set the position to read the public key, then load it
    KeyStream.SetSize(KeySizes[1]);
    KeyStream.Write(System.PByte(Buffer)[BufferSize - KeySizes[1] - SizeOf(KeySizes)],KeySizes[1]);
    RSASSA.PublicKey.LoadFromStream(KeyStream);
    //Set the position to read the signature, then read it
    Move(System.PByte(Buffer)[BufferSize - KeySizes[0] - KeySizes[1] - SizeOf(KeySizes)],SigBuf[0],KeySizes[0]);
    RSASSA.Signature.CopyBuffer(SigBuf[0],KeySizes[0]);
    //Reset the size and position
    ReAllocMem(Buffer,BufferSize - KeySizes[0] - KeySizes[1] - SizeOf(KeySizes));
    //If we can't verify the stream then fail
    If Not(RSASSA.VerifyBuffer(Buffer^,BufferSize - KeySizes[0] - KeySizes[1] - SizeOf(KeySizes))) Then Exit;
    //Reset the stream and decrypt it to OutStream
    OutStream.SetSize(BufferSize - KeySizes[0] - KeySizes[1] - SizeOf(KeySizes));
    BufferSize := AES.DecryptBuffer(Buffer^,BufferSize - KeySizes[0] - KeySizes[1] - SizeOf(KeySizes),OutStream.Memory^);
    OutStream.SetSize(BufferSize);
    //Reset the stream and get the compressed filesize
    OutStream.Position := 0;
    BufferSize := OutStream.Size;
    //Decompress the stream to file
    OutStream.Read(Buffer^,BufferSize);
  Finally
    //Free the streams
    OutStream.Free;
    KeyStream.Free;
  end;
  //If we made it here it probably happened error free
  Result := True;
end;
 
function SaveBufferToFile(const FileOut: String; Buffer: Pointer; BufferSize: DWORD): Boolean;
var
  hFile,
  BytesWritten : DWORD;
begin
  Result := False;
  hFile := CreateFile(PChar(FileOut),GENERIC_WRITE,0,nil,OPEN_ALWAYS,0,0);
  If hFile = INVALID_HANDLE_VALUE Then Exit;
  Try
    If (WriteFile(hFile,Buffer^,BufferSize,BytesWritten,nil)) And (BytesWritten = BufferSize) Then
      begin
      SetEndOfFile(hFile);
      Result := True;
    end;
  Finally
    CloseHandle(hFile);
  end;
end;
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:

Select allOpen in new window

 

by: ThievingSixPosted on 2009-08-20 at 06:21:53ID: 25142149

Oh, the line I pointed out is line 97.

 

by: den4bPosted on 2009-08-20 at 07:21:08ID: 25142841

You do a lot of raw memory management, which means the problem could be happening potentially anywhere in the code. First, I want to highlight this line:

System.PByte(BufferIn)[DataSize] := 0;

It seems you are accessing unallocated memory here, PByte(BufferIn) has [0..DataSize-1] elements, but you write 0 to PByte(BufferIn)[DataSize], which is outside of boundaries.

There are no other apparent problems in the code, from a simple inspection. I think you need to debug it in real-time, line by line, throughout entire file compression and decompression, checking all the variables for expected values. Especially check compression/decompression routines on dummy data, make sure it always gets it right. Then check your formats/headers, make sure they are written and read correctly.

Also, posted code is only for decompression, but remember that the problem may also be with the compression side of things, for example you didn't write your headers correctly, or data got cropped, etc.

If you are certain that problem happens from accessing lvFileList.Items[I].Data, you should defiantly check the code where you assign data to it and where you free it. Make sure you initialize all records.

Debugging, debugging, and more debugging... There is very little I can do from simple inspection of the snippet of code.

 

by: ThievingSixPosted on 2009-08-20 at 07:27:30ID: 25142925

Ha, I think you hit the nail on the head with your highlighted line. Which would make my addition of "+ 3" to the pointer enable it to not fail. The reason why I added this was because when the decompression routines run they do that as well for alignment issues.

The raw memory management would in effect have that one byte change run into something else which makes sense why it happens at the same time every time.

Thanks completely missed that typo!

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...