简体   繁体   English

vector :: clear()导致段错误

[英]vector::clear() causing a seg fault

I have a std::vector that is causing some very strange seg faults 我有一个std :: vector导致了一些非常奇怪的seg错误

//A.h
class A{
private:
  std::vector<float> data;
public:
  void set(const std::vector<float>& data);
};
//A.cpp
void A::set(const vector<float>& data){
  this->data.clear(); // crashes on this line
  for(float f : data) this->data.push_back(f);
}

Under what possible circumstances could vector::clear() cause a seg fault? 在什么可能的情况下,vector :: clear()可能导致段错误? I initially had 我最初有

void A::set(const vector<float>& data){
  this->data = data;
}

and had the same problem. 并有同样的问题。 I switched to the above to debug. 我切换到上面进行调试。 This is on gcc 4.7.2, x86_64 这是在gcc 4.7.2,x86_64上

IF it crashes precisely at the call to 'data.clear' (I mean, at exactly this line, not somewhere inside the clear), then be sure to check your this pointer at the faulting line. 如果它恰好在调用“ data.clear”时崩溃(我的意思是,恰好在此行,而不是在clear内部),那么请确保在故障行检查this指针。

If somehow your $this is null or trash-value due to accumulated effects of previous bugs, then this line might behave similarily. 如果由于先前错误的累积影响而使您的$ this为null或垃圾值,则此行的行为类似。

On the (almost) other hand, if it actually crashes somewhere inside the clear and you just have cut the stacktrace to make the problem description more succint, then still it is possible to be the same cause. 在另一方面,如果它实际上崩溃了,并且您只是剪切了堆栈跟踪以使问题描述更加简洁,那么仍然可能是相同的原因。

You may check the 'this' pointer for NULL easily in the debugger. 您可以在调试器中轻松检查'this'指针是否为NULL。 Also, detecting trashvalues is not hard: add some testfields to the A class, fill them in constructor with some predictable BUT NOT CONSTANT values, and when the app crashes, check if the this->mytestvalue is ok. 同样,检测垃圾值并不难:将一些测试字段添加到A类中,并在构造函数中填充一些可预测的但不是常量值,然后在应用程序崩溃时检查this-> mytestvalue是否正常。 If the $this is trashed, then the pointed test values will very often be almost random. 如果$ this被丢弃,则指向的测试值通常几乎是随机的。

Likely this is due to stack/memory corruption occurring somewhere else. 可能是由于堆栈/内存损坏在其他地方发生。 You should run your program with a memory checker, such as Valgrind using the memcheck tool to see what's going on. 您应该使用内存检查器(例如Valgrind)使用memcheck工具运行程序,以查看发生了什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM