title: C++ program error: malloc(): memory corruption
body: <p>C++ newbie and have been writing a C++ program, but it finally breaks at the point of calling a lib function call from ctime. </p>
  
  <p>The error shows info like this:<br>
  <strong><em>malloc(): memory corruption</em></strong></p>
  
  <p>AFAIK, this error(memory corruption) should be resulted from operate on out-of-bound memory address. And the print format represents YYYY-MM-DD-HH-MM, which is listed <a href="http://www.cplusplus.com/reference/ctime/strftime/" rel="nofollow noreferrer">here</a>, shows that the length should be definitively less than 100. </p>
  
  <p>Additional info:<br>
  - The program is compiled with flags: "-O3 -g -Wall -Wextra -Werror -std=c++17"<br>
  - Compiler: g++ 7.4.0<br>
  - System: WSL Ubuntu-18  </p>
  
  <p><strong><em>NOTE: This Code DOES NOT compiles and is NOT REPRODUCIBLE for the problem, See updates below</em></strong></p>
  
  <pre><code>/** class file **/
  #include &lt;sys/wait.h&gt;
  #include &lt;sys/types.h&gt;  
  #include &lt;unistd.h&gt;
  #include &lt;errno.h&gt;
  #include &lt;cstdlib&gt;
  #include &lt;iostream&gt;
  #include &lt;sstream&gt;
  #include &lt;string&gt;
  #include &lt;ios&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;algorithm&gt;
  #include &lt;cctype&gt;
  #include &lt;ctime&gt;
  #include &lt;limits&gt;
  #include "cache-proxy.hpp"
  
  static int PROXY_CONFIG = 0;
  
  void get_timestamp(char *buffer, int len);
  std::string get_cwd(void);
  
  CacheProxy::CacheProxy(__attribute__((unused)) const std::string&amp; node)
  { 
      curr_dir = fs::get_cwd();
      Logger::get().info("curr_dir " + curr_dir);
      proxy_path = "/usr/sbin/squid";
      std::string squid("squid");
  
      char buff[200];
      get_timestamp(buff, 200);    // error pops
      std::string proxy_config_path;
  
      /** plenty of codes following, but commented**/
  }
  
  void ~CacheProxy(){}
  
  void get_timestamp(char *buffer, int len)
  {
      time_t raw_time;
      struct tm *time_info;
      time(&amp;raw_time);
      time_info = std::localtime(&amp;raw_time);
      std::strftime(buffer, len, "%F-%H-%M", time_info);
      return;
  }
  
  // originally from other files, for convenient to be moved into this file 
  std::string get_cwd(void)
  {
      char path[PATH_MAX];
      std::string retval;
      if (getcwd(path, sizeof(path)) != NULL) {
          retval = std::string(path);
      } else {
          Logger::get().err("current_path", errno);
      }
      return retval;
  }
  
  
  /** header file **/ 
  #pragma once
  #include &lt;string&gt;
  
  class CacheProxy:
  {
  private:
      int server_pid;
      std::string proxy_path;
      std::string curr_dir;
      std::string squid_pid_path;
      ;
  
  public:
      CacheProxy(const std::string&amp;);
      ~CacheProxy() override;
  
  };
  
  /** main file **/
  int main(){
      Node node(); // the parameter is never used in the CacheProxy constructor though
      CacheProxy proxy(node); // error pops
      proxy.init();
  }
  
  </code></pre>
  
  <p>Thanks for any advices or thoughts. </p>
  
  <hr>
  
  <p>Updates:<br>
  code updated as above and there are three major files. The code shows the exact same sequences of the logic of my original codebase by leaving out irrelevant codes(I commented them out when run into the errors), but please forgive me in giving out such rough codes. </p>
  
  <p>Basically the the error pops during the object initialization and I currently assume that problems be either in get_cwd or localtime. </p>
  
  <p>Please indicate if you need more infomations, though I think other codes are non-relevant indeed. </p>
  
  <hr>
  
  <p>Updates Dec 21:<br>
  After commenting out different parts of the original code, I managed to locate the error part but cannot fix the bug. Opinions from comments are indeed true that the memory corruption error should originated from somewhere beforehand, however, what I am going to do to fix this problem, is somewhat different from other answers since I use setcap for my program and cannot use valgrind in this scenarios. </p>
  
  <p>I used another tool called ASan(<a href="https://clang.llvm.org/docs/AddressSanitizer.html" rel="nofollow noreferrer">Address Sanitizer</a>) to do the memory check. It was really easy to find out where the memory corruption is originated from with the tool and it has comprehensive analysis when the error occurs at runtime. I added support in the compiler and found out the main problem in my case is the memory allocation for string variables in CacheProxy class. </p>
  
  <p>So far, it has turned out to be another problem which is "why there are indirect memory leakages originated from allocating memory for string objects when 
   constructor of this class is called", which I will not collapsed here in this question.</p>
  
  <p>But it is really a good lesson for me that Memory problems actually have various types and causes, you cannot stare onto the source code for solving a problem which is not "index out of bound" or "illegal address access"(segfault) problem. Many tools are really handy and specialized in dealing with these things, so go and grab your tools.</p>