Recent

Author Topic: Counter changed after accessed  (Read 1395 times)

sunTan

  • Newbie
  • Posts: 2
Counter changed after accessed
« on: July 26, 2021, 04:08:44 am »
Hi,

I wrote earlier (Compilation error??) and I had issue removing the include files. My problem was counter altered from 0 after accessing the array.

            newcat := cbxCategory.Text ;
            catDB[catCnt] := newcat ;
            catCnt := catCnt + 1 ;
            frmMyDB.StatusBar.Panels.Items[0].Text := 'Category ' + newcat + ' saved.' ;

newcat was included for debugging purpose. If you breakpoint in TfrmMyDB.cbxCategoryKeyUp, catCnt = 0, on first encounter. After executing carDB[catCnt], catCnt value is changed from 0 to >17000. As a result, the system will break on error when catCnt is used.

Included is the bare minimum of the code.

Thanking you in advance... sunTan

rsz

  • New Member
  • *
  • Posts: 45
Re: Counter changed after accessed
« Reply #1 on: July 26, 2021, 07:01:07 am »
Hi, you are corrupting memory. Take a look, catCnt is set to 0 but the array catDB starts at 1 and you set catDB[0].

Code: Pascal  [Select][+][-]
  1. var
  2.   newcat  : string[16] ;  // new category string
  3.   catCnt  : Integer;
  4.   catDB   : array[1..1024] of String[16] ;
  5.  
  6. implementation
  7.  
  8. procedure TfrmMyDB.FormCreate(Sender: TObject);
  9. begin
  10.   //...
  11.   catCnt := 0 ;      // reset total category count
  12.   //...
  13. end;
  14.  
  15. procedure TfrmMyDB.cbxCategoryKeyUp(Sender: TObject; var Key: Word;
  16.   Shift: TShiftState);
  17. begin
  18.   //...
  19.   catDB[catCnt] := newcat ;
  20.   //...
  21. end;

I recommend using Low and High wherever possible:
https://www.freepascal.org/docs-html/rtl/system/low.html
https://www.freepascal.org/docs-html/rtl/system/high.html

It is also advisable to create the default debug and release build modes and to build and run with the debug mode because checks and assertions (range check) would have caught this. In this case it throws an exception on line 700 where you assign out of range.
https://wiki.freepascal.org/IDE_Window:_Compiler_Options#Adding_a_release_and_debug_build_modes

 

TinyPortal © 2005-2018