How to detect memory leaks in C++

The original article of this in Japanese was written in 2007, so the content may be outdated and unusable.

A memory leak occurred in a project that use C++ on Linux.
I tried to use MemProfmtraceccmallocmpatrol、and dmalloc, but only mtrace was available in the project environment.

However, in the case of new/delete, the existence of the leak was confirmed, but the source file name and line number were not output (in the case of malloc/free, even the line number is output). It seems that dmalloc can be used with c++ new/delete, but when I tried to link it with the target program, I got a link error and cannot use it.

After looking up the relevant information, I had no choice, so I tried to write the code myself.

The codes override or overload new, new[], delete, delete[], and check the correspondence at the time of memory allocation and release. If memory has been allocated but not released, the file name and line number on the source that allocated the memory are displayed.
1. Copy DetectMemoryLeaks.h and DetectMemoryLeaks.cpp to your project.
2. Add DetectMemoryLeaks.cpp to the target of compile.
3. Add the following codes at top of source code file which be compiled at first.
    #include “MemoryLeakChecker.h”
    #define new new(__FILE__, __LINE__ )
4. Add the following code at the start of the range where you want to check for memory leaks.
    memoryLeakCheckerCheckStart(std::cout);
5. Add the following code at the end of the range where you want to check for memory leaks.
    memoryLeakCheckerCheckEnd(std::cout);
6. Compile your codes, and run it.
Example to use.(MemoryLeaksSample.cpp)。
Note: Multithreading is not considered, nesting of the detectMemoryLeaksStart/End call is not considered.

DetectMemoryLeaks.cpp

std::map detectMemoryLeaksMemoryMap;
bool detectMemoryLeaksFlag = false;

void *
operator new(std::size_t size, char * pszFileName, int nLineNum)
throw (std::bad_alloc)
{
void * address = malloc(size);
if(address == 0)
throw std::bad_alloc();

if(detectMemoryLeaksFlag){
// std::cout << “new: ” << pszFileName << “:” << nLineNum << ” size=” << size << ” address=” << address << std::endl;
std::ostringstream oss;
oss << pszFileName << “:” << nLineNum << ” size=” << size  << ” address=” << address;
detectMemoryLeaksMemoryMap.insert( std::pair((std::size_t)address, oss.str()) );
}
return address;
}

void *
operator new[](std::size_t size, char * pszFileName, int nLineNum)
throw (std::bad_alloc)
{
void * address = malloc(size);
if(address == 0)
throw std::bad_alloc();

if(detectMemoryLeaksFlag){
// std::cout << “new[]: ” << pszFileName << “:” << nLineNum << ” size=” << size << ” address=” << address << std::endl;
std::ostringstream oss;
oss << pszFileName << “:” << nLineNum << ” size=” << size  << ” address=” << address;
detectMemoryLeaksMemoryMap.insert( std::pair((std::size_t)address, oss.str()) );
}
return address;
}

void
operator delete(void * address)
{
if(address == 0) // Depends on environment.
return;

if(detectMemoryLeaksFlag){
// std::cout << “delete: ” << ” address=” << address << std::endl;
std::map::iterator it = detectMemoryLeaksMemoryMap.begin();
std::map::iterator itEnd = detectMemoryLeaksMemoryMap.end();
std::size_t checkAddress = (std::size_t)address;
for(; it!=itEnd; it++){
if(it->first == checkAddress){
detectMemoryLeaksMemoryMap.erase(it);
break;
}
}
}
free(address);
}

void
operator delete[](void * address)
{
if(address == 0) // Depends on environment.
return;

if(detectMemoryLeaksFlag){
// std::cout << “delete[]: ” << ” address=” << address << std::endl;
std::map::iterator it = detectMemoryLeaksMemoryMap.begin();
std::map::iterator itEnd = detectMemoryLeaksMemoryMap.end();
std::size_t checkAddress = (std::size_t)address;
for(; it!=itEnd; it++){
if(it->first == checkAddress){
detectMemoryLeaksMemoryMap.erase(it);
break;
}
}
}
fr
ee(address);
}

void
detectMemoryLeaksStart(std::ostream& ros)
{
ros << “[detect memory leaks] start” << std::endl;
detectMemoryLeaksFlag = true;
}

void
detectMemoryLeaksEnd(std::ostream& ros)
{
ros << “[detect memory leaks] end” << std::endl;
if(detectMemoryLeaksMemoryMap.size() > 0){
ros << “memory leaks …” << std::endl;
std::map::iterator it = detectMemoryLeaksMemoryMap.begin();
std::map::iterator itEnd = detectMemoryLeaksMemoryMap.end();
for(; it!=itEnd; it++)
ros << ”  ” << it->second << std::endl;
}else{
ros << “memory leak is nothing.” << std::endl;
}
detectMemoryLeaksFlag = false;
detectMemoryLeaksMemoryMap.clear();
}

Install Jetpack to WordPress on lighttpd

error: site_inaccessible, IXR -32300
lighttpd 1.4.28, WordPress 3.4.2–ja, Jetpack 1.9.2, Core Control 1.1

http://techdevian.com/jetpack-error-failed-authenticate-resolved-fix/

  1. Core Control Plugin
  2. Tool -> Core Control -> HTTP Access Module 1.0 -> Save Module Choices
  3. External HTTP Access
  4. Manage Transports -> cURL Transport -> Disable Transport

http://en.forums.wordpress.com/topic/jetpack-instl-issue-with-ssl-and-lighttpd?replies=18
/etc/lighttpd/lighttpd.conf
url.rewrite-once = (
"^/en//(.*)\.(.+)$" => "$0",
"^/en/(wp-.+)$" => "$0",
"^/en/xmlrpc.php(.*)?" => "$0",
"^/en/sitemap.xml" => "$0",
"^/en/(.+)/?$" => "/en/index.php/$1",
"^/ja//(.*)\.(.+)$" => "$0",
"^/ja/(wp-.+)$" => "$0",
"^/ja/xmlrpc.php(.*)?" => "$0",
"^/ja/sitemap.xml" => "$0",
"^/ja/(.+)/?$" => "/ja/index.php/$1"
)

We can confirm by http://userwordpressdomain/yourwordpressdirectory/xmlrpc.php?rsd

[Scala] Solution for nested match statements (for practice)

practice about https://gist.github.com/2382341.

// see https://gist.github.com/2382341

// scalaz for only solution3
import scalaz._
import Scalaz._

object SolutionForMultiNestedMatchforMyStudy {

  def f(num: Int): Option[Int] = {
    num match {
      case 0 => Some(1)
      case 1 => Some(2)
      case 2 => Some(3)
      case _ => None
    }
  }

  def solution1(num: Int): Int = {
    f(num) match {
      case Some(v1) => {
        f(v1) match {
          case Some(v2) => {
            f(v2) match {
              case Some(v3) => v3
              case _ => -3
            }
          }
          case _ => -2
        }
      }
      case _ => -1
    }
  }

  def solution2(num: Int): Int = {
    val v1 = f(num)
    val v2 = v1.flatMap(f)
    val v3 = v2.flatMap(f)

    (v1, v2, v3) match {
      case (Some(_), Some(_), Some(result)) => result
      case (Some(_), Some(_), None) => -3
      case (Some(_), None, None) => -2
      case _ => -1
    }
  }

  def solution3(num: Int): Int = {
    f(num).toSuccess(-1).flatMap(f(_).toSuccess(-2)).flatMap(f(_).toSuccess(-3)).fold(identity, a => a)
  }

  def solution4(num: Int): Int = {
    (for {
      v1 <- f(num).toRight(-1).right
      v2 <- f(v1).toRight(-2).right
      v3 <- f(v2).toRight(-3).right
    } yield v3).merge
  }

  def solution5(num: Int): Int = {
    val v1 = f(num).getOrElse { return -1 }
    val v2 = f(v1).getOrElse { return -2 }
    f(v2).getOrElse { return -3 }
  }

  def example {
    (0 to 3).foreach{n => println(solution1(n))}
    println
    
    (0 to 3).foreach{n => println(solution2(n))}
    println
    
    (0 to 3).foreach{n => println(solution3(n))}
    println
    
    (0 to 3).foreach{n => println(solution4(n))}
    println
    
    (0 to 3).foreach{n => println(solution5(n))}
  }
}

Converting hex string and byte array by Scala fixed

Converting hex string to byte array, and byte array to hex string by Scala. Fixed to remove string except hex.

object HexBytesUtil {

  def hex2bytes(hex: String): Array[Byte] = {
    hex.replaceAll("[^0-9A-Fa-f]", "").sliding(2, 2).toArray.map(Integer.parseInt(_, 16).toByte)
  }

  def bytes2hex(bytes: Array[Byte], sep: Option[String] = None): String = {
    sep match {
      case None => bytes.map("%02x".format(_)).mkString
      case _ => bytes.map("%02x".format(_)).mkString(sep.get)
    }
    // bytes.foreach(println)
  }

  def example {
    val data = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21 21"
    val bytes = hex2bytes(data)
    println(bytes2hex(bytes, Option(" ")))

    val data2 = "48-65-6C-6C-6F-20-57-6F-72-6C-64-21-21"
    val bytes2 = hex2bytes(data2)
    println(bytes2hex(bytes2, Option("-")))

    val data3 = "48656C6C6F20576F726C642121"
    val bytes3 = hex2bytes(data3)
    println(bytes2hex(bytes3))
  }

}

Converting hex string and byte array by Scala

Converting hex string to byte array, and byte array to hex string by Scala.

Anti-nuclear protesters rally outside Japan prime minister’s office on 29 June, 2012

Anti-nuclear protesters rally outside Japan prime minister’s office on 29 June, 2012. 150,000-200,000 people. (The police said 17,000 people.)
Before last time was 45,000 people on 22 June. (The police said 11,000 people.)

https://twitter.com/ishii_maki/status/218706050663198721/photo/1
https://twitter.com/ishii_maki/status/218712324066902016/photo/1
https://twitter.com/ishii_maki/status/218721235264217088/photo/1

http://mainichi.jp/graph/2012/06/30/20120630k0000m040057000c/001.html
http://www.asahi.com/national/update/0629/TKY201206290577.html
http://sankei.jp.msn.com/life/news/120629/trd12062923270026-n1.htm
http://www.fnn-news.com/news/headlines/articles/CONN00226467.html