type
status
date
slug
summary
tags
category
icon
password
😀
所有权是确保rust程序安全的一种机制 安全:程序中没有未定义的行为
 

所有权

notion image
 
notion image
notion image
notion image
notion image
notion image
答案是两个
notion image
notion image
notion image
notion image
notion image
 
notion image
 
notion image
notion image
notion image

作业

notion image
我的答案
首先什么是未定义的行为 就是说软件没有指定的没有考虑到的情况
首先,让我们澄清一下编译错误未定义行为 (UB) 之间的区别:
  • 编译错误 (Compile Error):当你的代码违反了语言的语法类型规则时发生。编译器会阻止程序生成可执行文件,因为代码从结构上就是错误的(比如少了一个分号)。这是一种明确定义的行为:编译器必须报告错误。
  • 未定义行为 (Undefined Behavior, UB):当你的代码在运行时违反了语言标准的一些假设或规则时发生。编译器通常无法在编译阶段发现它。当 UB 发生时,程序可能会做任何事情:看起来正常、崩溃、产生错误结果,甚至格式化你的硬盘(理论上)
仅仅去使存储一个被释放内存的地址不是UB
使用就是ub了

为什么 “再次释放” 是 UB?

  • 🦀 Rust 视角:Rust 的所有权系统会在编译时(Compile Time)防止这种情况发生,因为一旦内存被释放,它就不会再有一个有效的所有者或可变的借用者去操作它。
  • ⚙️ C/C++ 视角:当第一次调用 free() 时,内存管理系统会修改堆 (Heap) 上的一些内部数据结构(例如,将该块标记为空闲,并可能将其添加到空闲列表)。再次调用 free() 时,系统会尝试用一个可能已经损坏或不再有效的指针来重复修改这些内部结构,这几乎肯定会导致堆损坏 (heap corruption),结果是完全不可预测的。
选项2 不是ub
选项4 是一个明确定义行为 因为会出现问题。
notion image
很清晰 1 2 4会ub
 
rust 引用和借用上rust 函数&控制语句
Loading...