FillMemory、ZeroMemory 一目了然的兩個函數, 但其實它們都是調用了 FillChar;
清空不過就是填充空字符(#0: 編號為 0 的字符), 說來說去是一回事.
為了下面的測試, 先寫一個以十六進制方式查看內存的函數:
function GetMemBytes(var X; size: Integer): string; var pb: PByte; i: Integer; begin pb := PByte(X); for i := 0 to size - 1 do begin Result := Result + IntToHex(pb^, 2) + #32; Inc(pb); end; end; {GetMemBytes end} // 測試: var p1: PAnsiChar; p2: PWideChar; s1: AnsiString; s2: UnicodeString; begin p1 := 'ABCD'; p2 := 'ABCD'; s1 := 'ABCD'; s2 := 'ABCD'; ShowMessage(GetMemBytes(p1,4)); {41 42 43 44} ShowMessage(GetMemBytes(p2,8)); {41 00 42 00 43 00 44 00} ShowMessage(GetMemBytes(s1,4)); {41 42 43 44} ShowMessage(GetMemBytes(s2,8)); {41 00 42 00 43 00 44 00} end;
測試 FillMemory、ZeroMemory、FillChar 三個填充函數:
const num = 10; var p: PChar; begin p := StrAlloc(num); ShowMessage(GetMemBytes(p, num)); {從結果看出 StrAlloc 沒有初始化內存} FillMemory(p, num, Byte('A')); ShowMessage(GetMemBytes(p, num)); {41 41 41 41 41 41 41 41 41 41} ZeroMemory(p, num); ShowMessage(GetMemBytes(p, num)); {00 00 00 00 00 00 00 00 00 00} FillChar(p^, num, 'B'); ShowMessage(GetMemBytes(p, num)); {42 42 42 42 42 42 42 42 42 42} StrDispose(p); end;
此時, 我想到一個問題:
GetMem 和 GetMemory 沒有初始化內存; AllocMem 會初始化內存為空, 那么
ReallocMem、ReallocMemory 會不會初始化內存?
測試一下(結果是沒有初始化):
{測試1} var p: Pointer; begin p := GetMemory(3); ShowMessage(GetMemBytes(p, 3)); ReallocMem(p, 10); ShowMessage(GetMemBytes(p, 10)); {沒有初始化} FreeMemory(p); end; {測試2} var p: Pointer; begin p := AllocMem(3); ShowMessage(GetMemBytes(p, 3)); ReallocMem(p, 10); ShowMessage(GetMemBytes(p, 10)); {沒有初始化} FreeMemory(p); end;
另外: FillMemory、ZeroMemory 的操作對象是指針, 而 FillChar 的操作對象則是實體.