Registriert seit: 16. Jan 2004
Ort: Bendorf
5.219 Beiträge
Delphi 10.2 Tokyo Professional
|
Meine Funktion hinterlässt Memoryleaks
30. Mär 2008, 18:12
Hi,
Habe hier folgende Funktion. Ich schreibe da mit WriteProcessMemory in den Speicher des Taskmanagers.
Blöderweise steigt der Speicherverbrauch des Taskmanagers alle 2 Sekunden ca. um 2 MB....
Delphi-Quellcode:
function GetTaskManagerItemText(Index: Integer = -1): String;
var wnd1,wnd2,ListView: hwnd;
ItemLoc,ItemGlob: PLVItemA;
pid: Cardinal;
hProc: THandle;
Buffer: Array[0..255] of Char;
bw: Cardinal;
begin
Result := '[Error]';
wnd1 := FindWindow('#32770',nil);
wnd2 := FindWindowEx(wnd1,0,'#32770',nil);
ListView := FindWindowEx(wnd2,0,'SysListView32',nil);
if ListView <> 0 then
begin
GetWindowThreadProcessID(wnd1,pid);
hProc := OpenProcess(PROCESS_VM_OPERATION or PROCESS_VM_READ or PROCESS_VM_WRITE,
false,pid);
if hProc <> 0 then
begin
ItemLoc := VirtualAlloc(nil,SizeOf(TLVItemA),MEM_RESERVE or MEM_COMMIT, PAGE_READWRITE);
ItemGlob := VirtualAllocEx(hProc,nil,SizeOf(TLVITemA)+SizeOf(Buffer),
MEM_RESERVE or MEM_COMMIT, PAGE_READWRITE);
end
else
exit;
try
if Index = -1 then
Index := SendMessage(ListView,LVM_GETSELECTIONMARK, 0, 0);
with ItemLoc^ do
begin
mask := LVIF_TEXT;
iItem := Index;
iSubItem := 0;
pszText := PChar(Cardinal(ItemGlob)+SizeOf(TLVItemA));
cchTextMax := SizeOf(Buffer);
end;
WriteProcessMemory(hProc,ItemGlob,ItemLoc,SizeOf(TLVITemA),bw);
ListView_GetItem(Listview,ItemGlob^);
ReadProcessMemory(hProc,Pointer(Cardinal(ItemGlob)+SizeOf(TLVItemA)),@Buffer[0],256,bw);
Result := Buffer;
finally
VirtualFreeEx(hProc,ItemGlob,SizeOf(TLVITemA)+SizeOf(Buffer),MEM_FREE or MEM_DECOMMIT or MEM_RELEASE);
VirtualFree(ItemLoc,SizeOf(TLVItemA),MEM_FREE or MEM_DECOMMIT or MEM_RELEASE);
CloseHandle(hProc);
end;
end;
end;
Und in diesem Thread wird die Funktion aufgerufen:
Delphi-Quellcode:
procedure AThread;
begin
while not ThreadTerminated do
begin
if GetTaskManagerItemText = Filename then
// DoSomething
Sleep(1);
end;
end;
Wo habe ich jetzt hier den Fehler drin?
Gruß
Neutral General
Michael "Programmers talk about software development on weekends, vacations, and over meals not because they lack imagination,
but because their imagination reveals worlds that others cannot see."
|