In the following code, after calling a deleted object (B: tbitmap) event, an access violation occurs: VaR B: tbitmap; Begin B: = tbitmap. Create; Try // Perform some operations on object B Finally B. Free; End; ... // Because B has been released, an access violation error will occur. B. Canvas. textout (0, 0, 'This is an access violation '); End; 2. nonexistent API Parameters If you try to pass a non-existent parameter to the win API function, an access violation error will occur. The best way to solve this access violation error is to check the win api help to see the parameter information and parameter type of this API function call. For example, always do not pass an invalid pointer to a buffer Parameter 3. Release Delphi When an object has another object, let it delete it for you. By default, all forms (automatically created) belong to the Application object. When an Application ends, it releases the Application object and releases all forms. For example, if you automatically create two forms (Form1/Unit1 and Form2/Unit2) at the beginning of the program, the following code will cause Access violation errors: Unit Unit1; ... Uses unit2; ... Procedure TForm1.Call _ Form2 Begin Form2.ShowModal; Form2.Free; // Access violation error will appear Form2.ShowModal; End; 4. Killing an exception Never destroy the temporary exception object (E). When an exception is handled, the exception object is automatically released. If you manually release the exception object, the program will try to release it again, and the Access violation error will occur: Zero: = 0; Try Dummy: = 10/Zero; Except On E: EZeroDivide do MessageDlg ('Do not use 0 as the divisor! ', MtError, [mbOK], 0 ); E. free. // Access violation error will appear End; 5. Retrieve an empty string A Null String does not have any data. That is to say, retrieving an empty string is equivalent to accessing a non-existent object, which will lead to an Access violation error: Var s: string; Begin S: = ''; S [1]: = 'a '; // Access violation error will appear End; 6. Direct Pointer Reference You must indirectly reference the pointer. Otherwise, you will change the pointer address and possibly destroy other storage units: Procedure TForm1.Button1Click (Sender: TObject ); Var P1: pointer; P2: pointer; Begin GetMem (p1, 128 ); GetMem (p2, 128 ); // Access violation error caused by the next row Move (p1, p2, 128 ); // The method for the next row is correct Move (p1 ^, p2 ^, 128 ); FreeMem (p1, 128); [Page] FreeMem (p2, 128 ); End; These are all my suggestions on Access Violation errors during runtime. I hope you can also give some comments on Access Violation errors in your program. Comment by the old cat: I believe that all readers have encountered the "Access violation" error. If it is not our own program, many of us will put the responsibility on Bill Gates. If your program encounters this embarrassing error, how can we explain it to users? This article is the best answer. |