Share via


错误:heap-use-after-free

地址清理器错误:使用解除分配的内存

我们演示了三个示例,其中堆中的存储可以通过 mallocrealloc (C) 和 new (C++) 进行分配,以及错误使用 volatile

示例 - malloc

// example1.cpp
// heap-use-after-free error
#include <stdlib.h>

int main() {
  char *x = (char*)malloc(10 * sizeof(char));
  free(x);

  // ...

  return x[5];   // Boom!
}

若要生成并测试此示例,请在 Visual Studio 2019 版本 16.9 或更高版本的开发人员命令提示符中运行以下命令:

cl example1.cpp /fsanitize=address /Zi
devenv /debugexe example1.exe

出现 Visual Studio 时,按F5运行示例 1。

生成的错误

Screenshot of the debugger displaying use of deallocated memory error for example 1.

引发的异常对话框指向第 11 行,return x [ 5 ],并说: 地址清理器错误使用解除分配的内存。 屏幕截图中未显示控制台窗口中的输出,其中显示了内存地址,以及用于确定可寻址字节、部分可寻址字节、释放堆区域和错误区域中堆剩余红色区域字节的键。

示例 - operator new

// example2.cpp
// heap-use-after-free error
#include <windows.h>

int main() {
  char *buffer = new char[42];
  delete [] buffer;

  // ...

  buffer[0] = 42;  // Boom!
  return 0;
}

若要生成并测试此示例,请在 Visual Studio 2019 版本 16.9 或更高版本的开发人员命令提示符中运行以下命令:

cl example2.cpp /fsanitize=address /Zi
devenv /debugexe example2.exe

出现 Visual Studio 时,按F5运行示例 2。

生成的错误 - operator new

Screenshot of the debugger displaying use of deallocated memory error in example 2.

引发的异常对话框指向第 11 行,buffer[0] = 42,,并说: 地址清理器错误使用解除分配的内存。 屏幕截图中未显示控制台窗口中的输出,其中显示了内存地址,以及用于确定可寻址字节、部分可寻址字节、释放堆区域和错误区域中堆剩余 alloca 红色区域字节的键。

示例 - realloc

// example3.cpp
// heap-use-after-free error
#include <malloc.h>

int main() {
  char *buffer = (char*)realloc(0, 42);
  free(buffer);

  // ...

  buffer[0] = 42;  // Boom!
  return 0;
}

若要生成并测试此示例,请在 Visual Studio 2019 版本 16.9 或更高版本的开发人员命令提示符中运行以下命令:

cl example3.cpp /fsanitize=address /Zi
devenv /debugexe example3.exe

出现 Visual Studio 时,按F5运行示例 3。

生成的错误 - realloc

Screenshot of the debugger displaying use of deallocated memory error in example 3.

引发的异常对话框指向第 11 行,buffer[0] = 42,,并说: 地址清理器错误使用解除分配的内存。 屏幕截图中未显示控制台窗口中的输出,其中显示了内存地址,以及用于确定可寻址字节、部分可寻址字节、释放堆区域和错误区域中堆剩余红色区域字节的键。

示例 - volatile

// example4.cpp
// heap-use-after-free error
#include <stdlib.h>

int main() {

  volatile char *x = (char*)malloc(sizeof(char));
  free((void*)x);

      //...

  *x = 42;        // Boom!
}

若要生成并测试此示例,请在 Visual Studio 2019 版本 16.9 或更高版本的开发人员命令提示符中运行以下命令:

cl example4.cpp /fsanitize=address /Zi
devenv /debugexe example4.exe

出现 Visual Studio 时,按F5运行示例 4。

生成的错误 - volatile

Screenshot of the debugger displaying a use of deallocated memory error in example 4.

引发的异常对话框指向第 12 行,*x = 42,并说: 地址清理器错误:使用解除分配的内存。 屏幕截图中未显示控制台窗口中的输出,其中显示了内存地址,以及用于确定可寻址字节、堆剩余红色区域字节以及错误区域中一些可寻址和部分可寻址字节的键。

另请参阅

AddressSanitizer 概述
AddressSanitizer 已知问题
AddressSanitizer 生成和语言参考
AddressSanitizer 运行时参考
AddressSanitizer 阴影字节
AddressSanitizer 云或分布式测试
AddressSanitizer 调试程序集成
AddressSanitizer 错误示例