首页 > 解决方案 > 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++ 中运行我的代码时,它运行良好并且计算正确,关于如何修复它的任何建议?

标签: c++

解决方案


positionstodelete在任何擦除之前约束向量 arr2 的索引。positionstodeleteeafter中的所有索引arr2.erase(arr2.begin() + positionstodelete[i])都失效了,arr2 的大小发生了变化。该消息报告您正在尝试通过超出范围的索引访问向量。

您应该用反向循环替换最后一个循环。


推荐阅读