为何出现AddressSanitizer: heap-buffer-overflow错误?求解答
堆缓冲区溢出错误分析及代码修复
错误根源
- temp向量越界访问:你初始化
temp时只分配了10个元素,但数组中不同元素的数量可能远多于10个。当k增长到10及以上时,temp[k]++会访问vector内存边界之外的区域,直接触发heap-buffer-overflow错误。 - 循环条件逻辑错误:标注的代码行
while (arr[i] == -1000 && i < 1000)里,用固定值1000作为i的边界完全不合理,应该使用数组的实际长度n。如果数组长度大于1000,i到1000后会继续访问arr[1000](越界);如果数组长度小于1000,循环会提前终止,导致后续元素未被处理。 - 重复检查范围错误:最后检查次数重复的循环中,你遍历了
n次,但temp里只有前k个元素是有效数据(对应不同元素的出现次数),遍历到n会访问temp的无效区域,要么触发越界,要么得到错误值。
修复后的代码(保留你的原始逻辑风格)
class Solution { public: bool uniqueOccurrences(vector<int>& arr) { // 改用动态扩容的方式存储次数,避免固定长度导致的越界 vector<int> temp; int n = arr.size(), i = 0; while (i < n) { int count = 0; for (int j = 0; j < n; j++) { if (arr[j] == arr[i]) { count++; arr[j] = -1000; } } temp.push_back(count); // 动态添加元素,不会越界 // 修正循环边界,使用数组实际长度n while (i < n && arr[i] == -1000) i++; } // 只遍历有效元素的范围,而非整个数组长度 int k = temp.size(); for (int i = 0; i < k; i++) for (int j = i + 1; j < k; j++) { if (temp[i] == temp[j]) return false; } return true; } };
更高效的优化方案(哈希表实现)
你的原始逻辑时间复杂度为O(n²),效率较低。用C++的unordered_map统计元素出现次数,unordered_set检查次数是否重复,代码更简洁高效(时间复杂度O(n)):
class Solution { public: bool uniqueOccurrences(vector<int>& arr) { unordered_map<int, int> countMap; // 统计每个元素的出现次数 for (int num : arr) { countMap[num]++; } unordered_set<int> countSet; // 将次数存入set,若插入失败说明存在重复 for (auto& [num, cnt] : countMap) { if (!countSet.insert(cnt).second) { return false; } } return true; } };
内容的提问来源于stack exchange,提问作者user20199678
相关产品推荐
相关产品推荐

