C++实现setZeroes矩阵置零报misaligned address运行时错误
问题现象
编写C++矩阵置零
setZeroes接口时抛出运行时异常:
Line 1034: Char 9: runtime error: reference binding to misaligned address 0xbebebebebebebebe for type 'int'
错误产生原因
- 地址
0xbebebebebebebebe是C++ Windows调试环境下对未分配/已释放内存的标记填充值,该异常本质是数组下标越界引发的非法内存访问。 - 核心错误是
make_zero函数中行列遍历的边界完全写反:- 置零指定行时,行号固定,需要遍历该行所有列,列的总数是
m,但原代码写的循环条件是j < n,当矩阵行列数不等时,要么无法覆盖整行所有列,要么触发列方向越界。 - 置零指定列时,列号固定,需要遍历该列所有行,行的总数是
n,但原代码写的循环条件是j < m,当m > n时,行下标j会超出矩阵的最大行索引n-1,访问不存在的内存地址,直接触发上述运行时错误。
- 置零指定行时,行号固定,需要遍历该行所有列,列的总数是
修复方案
- 调整
make_zero函数中两个循环的边界,严格匹配行列维度:- 置零行:列下标从0遍历到
m-1,循环判断条件为j < m - 置零列:行下标从0遍历到
n-1,循环判断条件为j < n
- 置零行:列下标从0遍历到
修复后可运行代码
class Solution { private: void make_zero(vector<vector<int>>& matrix, vector<pair<int,int>> zero_pos, int row_cnt, int col_cnt) { for(auto pos : zero_pos) { int target_row = pos.first; int target_col = pos.second; // 置零目标行 for(int j = 0; j < col_cnt; j++) { matrix[target_row][j] = 0; } // 置零目标列 for(int j = 0; j < row_cnt; j++) { matrix[j][target_col] = 0; } } } public: void setZeroes(vector<vector<int>>& matrix) { int row_cnt = matrix.size(); int col_cnt = matrix[0].size(); vector<pair<int,int>> zero_pos; // 先记录所有原始0的位置,避免置零过程干扰判断 for(int i = 0; i < row_cnt; i++) { for(int j = 0; j < col_cnt; j++) { if(matrix[i][j] == 0) { zero_pos.push_back({i,j}); } } } make_zero(matrix, zero_pos, row_cnt, col_cnt); } };
内容的提问来源于stack exchange,提问作者YASH TYAGI
相关产品推荐
相关产品推荐

