title: Why My Program works perfectly when it should have generated a core dump because of dangling pointer?
body: <p>I works on recommendation system. And my program contains the following code:</p>
  
  <pre><code>#include&lt;vector&gt;
  using namespace std;
  #define MAX_KEYWORD_NUM 2048
  struct keyword_t
  {
      char* str;
      int* p;
      //other stuff
  };
  class Myclass
  {
  public:
      bool add_keyword(keyword_t &amp;keyword);
      int getValueFromConfigurationFile(const char *);
      bool reset()
  private:
      vector&lt;keyword_t&gt;_keywords_vec;
      vector&lt;keyword_t*&gt;_pkeywords_vec;
      Myclass();
      //other stuff
  };
  Myclass::Myclass()
  {
      _keywords_vec.reserve(MAX_KEYWORD_NUM);
  }
  bool Myclass::reset()
  {
      _pkeywords_vec.clear();
      _keywords_vec.clear();
  }
  bool Myclass::add_keyword(keyword_t&amp; keyword)
  {
      int limit = getValueFromConfigurationFile("limit");
      int _keywords_num = _keywords_vec.size();
      if (_keywords_num &gt;= limit) 
      {
          return false;
      }
      _keywords_vec.push_back(keyword);
      keyword_t* p_kw = &amp;_keywords_vec[_keywords_num];
      _pkeywords_vec.push_back(p_kw);
      return true;
  }
  </code></pre>
  
  <p>I define an object of Myclass in a thread and this thread will continually process incoming requests using this object. </p>
  
  <p>Obviously, there is a potential problem in function add_keyword. That is if limit is greater than MAX_KEYWORD_NUM, _keywords_vec will be reallocated and all previous elements will probably be in different memory address. So, the pointers previously pushed into _pkeywords_vec will be dangling pointers and this will probably cause a core dump.</p>
  
  <p>I do several experiments on it. However I got conflicting results.</p>
  
  <p>Experiment A: </p>
  
  <p>set the "limit" in configuration file to :3000, start the program, and it soon generates a core dump within one or two minutes.</p>
  
  <p>Experiment B:</p>
  
  <p>set the "limit" in configuration file to :2048, start the program, and after several minutes, change it to 3000. it also soon generates a core dump.</p>
  
  <p>Experiment C:</p>
  
  <p>set the "limit" in configuration file to :2048, start the program, and after some six hours, change it to 3000. it DO NOT generate any core dump and works perfectly well even for several days. I have make sure that limit has been changed to 3000 in this case.</p>
  
  <p>All the experiments can be replicated.</p>
  
  <p>How to explain Experiment C? Since Experiment C has been replicated thousands of times (different random requests), it is not likely that this is only undefined behavior. The possibility to generate core dump is obviously greater in Experiment A and B. So there should be something different between A\B and C.</p>
  
  <p>Thanks.</p>