c++ - UndefinedBehaviorSanitizer 致命信号错误不知道该怎么办
问题描述
std::vector<int> deleteNth(std::vector<int> arr, int n)
{
std::vector<int> arr2 = arr;
std::vector<int> positionstodelete;
unsigned short counter;
unsigned short lengthofmotives = arr.size();
unsigned short currentnumber;
for (int i = 0; i < lengthofmotives-1; i++){
counter = 1;
currentnumber = i;
for(int i = currentnumber; i < lengthofmotives-1;i++){
if (arr2[currentnumber] == arr2[i+1]){
counter++;
if(counter > n){
positionstodelete.push_back(i+1);
counter--;
}
}
}
}
size_t postodelsize = positionstodelete.size();
counter = 0;
if (postodelsize > 0){
for (size_t i = 0; i < postodelsize;i++){
arr2.erase(arr2.begin() + positionstodelete[i]);
counter++;
}
}
return arr2;
}
当我在 codewars 中运行此代码时,我收到此错误
STDERR " UndefinedBehaviorSanitizer:DEADLYSIGNAL
==1==错误:UndefinedBehaviorSanitizer:SEGV 位于未知地址 0x0000016d8000(pc 0x7fe790e16cf1 bp 0x0000016ca390 sp 0x7ffe0cacc418 T1)
==1==该信号是由 READ 内存访问引起的。
==1==警告:外部符号的路径无效!
==1==警告:无法使用和重新启动外部符号!
#0 0x7fe790e16cf0 (/lib/x86_64-linux-gnu/libc.so.6+0x18ecf0)
#1 0x4258bd (/workspace/test+0x4258bd)
#2 0x4284a8 (/workspace/test+0x4284a8)
3 0x426aae (/workspace/test+0x426aae)
#4 0x4264dd (/workspace/test+0x4264dd)
#5 0x4261cb (/workspace/test+0x4261cb)
6 0x42c8d5 (/workspace/test+0x42c8d5)
#7 0x4259bd (/workspace/test+0x4259bd)
#8 0x7fe790ca9bf6 (/lib/x86_64-linux-gnu/libc.so.6+0x21bf6)
#9 0x4046f9 (/workspace/test+0x4046f9)
UndefinedBehaviorSanitizer 无法提供附加信息。
==1==中止”
这是什么意思?当我在 dev c++ 中运行我的代码时,它运行良好并且计算正确,关于如何修复它的任何建议?
解决方案
positionstodelete
在任何擦除之前约束向量 arr2 的索引。positionstodeletee
after中的所有索引arr2.erase(arr2.begin() + positionstodelete[i])
都失效了,arr2 的大小发生了变化。该消息报告您正在尝试通过超出范围的索引访问向量。
您应该用反向循环替换最后一个循环。
推荐阅读
- postgresql - 为什么有些 psql 行在数据库名称后有 (# 或 '#?
- reactjs - React 新手 :: 警告:列表中的每个孩子都应该有一个唯一的“关键”道具
- scala - 有没有办法在布尔 ZIO 测试中添加描述性断言消息
- python - 压缩大型 GeoJSON/Shapefle 数据集以在 Web 浏览器上查看
- node.js - MongoDB:如何将仅出现在 $project 中的字段相乘?
- javascript - Javascript拆分URL并选择要放置在表格中的字符串
- java - 如何在java中的PriorityBlockingQueue中添加毒丸?
- c# - 多米诺骨牌的数据类型
- git - 具有多个命令的 Git 别名
- delphi - DELPHI - 有没有办法释放在运行时创建的对象而不会出现“访问冲突”?