清空和填充內存

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 的操作对象则是实体.

posted @ 2009-09-29 09:39  delphi中间件  阅读(278)  评论(0编辑  收藏  举报