• FillMemory()、ZeroMemory(),fillchar()


     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;

  • 相关阅读:
    LINQ to SQL 运行时动态构建查询条件
    MVC ViewData和ViewBag
    下面介绍一下 Yii2.0 对数据库 查询的一些简单的操作
    php表单中如何获取单选按钮与复选按钮的值
    [moka同学摘录]Yii2.0开发初学者必看
    Yii路径总结
    css样式reset
    ajax onblur 用法
    jquery自定义插件——window的实现
    jQuery使用ajaxStart()和ajaxStop()方法
  • 原文地址:https://www.cnblogs.com/hnxxcxg/p/2940799.html
Copyright © 2020-2023  润新知