出现运行时错误:引用绑定到未对齐地址,int类型需4字节对齐
错误原因排查
- 核心问题:边界指针错误地在遍历循环体内更新
代码中四个遍历方向的循环里,top++、right--、bottom--、left++被放在了循环体内部,导致每遍历一个元素就修改边界指针,直接破坏了遍历逻辑:- 第一个横向遍历循环中,每添加一个元素就执行
top++,会让top快速超出矩阵行范围,后续访问matrix[top][...]时触发越界内存访问,这就是UndefinedBehaviorSanitizer报错的根本原因(0xbebebebe是无效内存的填充标记)。 - 其余三个循环的边界更新逻辑同理,会导致后续遍历的边界条件混乱,进一步引发非法内存访问。
- 第一个横向遍历循环中,每添加一个元素就执行
修复方案
将所有边界指针的更新操作从循环体内部移到循环结束后,确保完整遍历当前边后再移动边界:
vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> ans; if (matrix.empty()) return ans; // 新增空矩阵判断,避免访问matrix[0]出错 int row = matrix.size(); int col = matrix[0].size(); int top = 0; int bottom = row - 1; int left = 0; int right = col - 1; while (top <= bottom && left <= right) { // 从左到右遍历顶行 for (int j = left; j <= right; j++) { ans.push_back(matrix[top][j]); } top++; // 遍历完顶行后,top下移 // 从上到下遍历右列 for (int i = top; i <= bottom; i++) { ans.push_back(matrix[i][right]); } right--; // 遍历完右列后,right左移 // 从右到左遍历底行(需判断top <= bottom,避免单行重复遍历) if (top <= bottom) { for (int j = right; j >= left; j--) { ans.push_back(matrix[bottom][j]); } bottom--; // 遍历完底行后,bottom上移 } // 从下到上遍历左列(需判断left <= right,避免单列重复遍历) if (left <= right) { for (int i = bottom; i >= top; i--) { ans.push_back(matrix[i][left]); } left++; // 遍历完左列后,left右移 } } return ans; }
- 额外优化:新增
if (matrix.empty()) return ans;判断,避免当输入矩阵为空时,访问matrix[0].size()触发的未定义行为。
内容的提问来源于stack exchange,提问作者Tanmay Bansal
相关产品推荐
相关产品推荐

