zoukankan      html  css  js  c++  java
  • Delphi 的内存操作函数(4): 清空与填充内存


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

  • 相关阅读:
    WeX5 苹果APP打包教程
    开源中国社区
    HBuilder-飞速编码的极客工具,手指爽,眼睛爽下载
    java用double和float进行小数计算精度不准确
    SQL Server 查询表的主键的两种方式
    JS代码压缩格式化在线地址
    解决SQL Server 阻止了对组件 'Ad Hoc Distributed Queries' 的 STATEMENT'OpenRowset/OpenDatasource' 的访问的方法
    SQL跨数据库复制表数据
    ExtJs 扩展类CheckColumn的使用(事件触发)
    DM36x IPNC OSD显示中文 --- 基本数据准备篇
  • 原文地址:https://www.cnblogs.com/del/p/1333425.html
Copyright © 2011-2022 走看看