2
Well, I’m trying to use this Procedure to delete array items:
Before I declared in Type:
TStringArray = array of string;
In public:
filestoadd : TStringArray;
And no create:
for x:=0 to 5 do begin
SetLength(filestoadd, x);
filestoadd[x] := IntToStr(x)+'test';
end;
The first:
procedure DeleteElement(anArray:TStringArray;const aPosition:integer);
var
lg, j : integer;
begin
lg := length(anArray);
if Length(anArray) < aPosition then
exit;
if aPosition = lg-1 then
exit
else if aPosition = lg-1 then begin //if is the last element
//if TSomeType is a TObject descendant don't forget to free it
//for example anArray[aPosition].free;
Setlength(anArray, lg -1);
exit;
end;
for j := aPosition to lg-2 do//we move all elements from aPosition+1 left...
anArray[j] := anArray[j+1];//...with a position
SetLength(anArray, lg-1);//now we have one element less
//that's all...
end;
I’m trying to use it like this:
DeleteElement(filestoadd, ListBox1.ItemIndex)
But when using, gives access to Violation 0040989C. The error line is exactly the line that calls Function:
First chance Exception at $004098C8. Exception class $C0000005 with message 'access Violation at 0x004098c8: read of address 0xfffffffffc'. Process Exegenerator.exe (5808)
How can I fix it?
Nothing yet. I’ve already edited the post.
– Gabriel Sales
Try to run the program in the Debugger, and insert a breakpoint just before the Precedent by executing instruction by instruction. In the Debugger it will be possible to verify that all variables are correctly allocated. It is also likely that some memory violation is occurring elsewhere and that it is only appearing when this Procedure is executed (Undefined behavior).
– Vinícius Gobbo A. de Oliveira
Showed the same line.
– Gabriel Sales
I tested here in a short program and found no problems. I believe that the problem is elsewhere in your program that is causing Undefined behavior, and then on this line is arising the Segmentation fault. Without more information, I can’t go any further.
– Vinícius Gobbo A. de Oliveira
Strange, because taking that line (that calls the function), does not give the error.
– Gabriel Sales
That’s why it’s called
undefined behavior
. The behavior is random. It’s one of the worst problems there is, because the cause could be anything. Only a great knowledge of the language documentation, the libraries being used and good practices to avoid this type of error. If you put more code in the question, I’m sure I can help more. I just want to point out that I’m a little rusty in Delphi, but these theories apply to the vast majority of languages, including Delphi.– Vinícius Gobbo A. de Oliveira
Ah! One more thing I have just noticed that proves my theory. I will change my answer.
– Vinícius Gobbo A. de Oliveira
I’ll see what I can do, if I can, put it here.
– Gabriel Sales