valgrind可以用来检测内存泄漏等问题,在ubuntu下的例子程序如下:

#include
#include
#include

class String
{
public:
        String();
        String(const char *s);
        ~String();

        // 赋值函数
        String & operator=(const String &other);

        // 相加函数,如果没有friend修饰则只许有一个右侧参数
        friend String operator+( const String &s1, const String &s2);

        // print
        void print(void);

private:
        char *m_data;

};

String::String()
{
        printf("in constructor\n");
        m_data = new char[1];
}

String::String(const char *s)
{
        if (s == NULL) return;

        printf("%s:in constructor\n", s);
        m_data = new char[strlen(s)+1];
        strcpy(m_data, s);
}
 

String::~String()
{
        printf("%s:in destructor\n", m_data);
        delete [] m_data;
}

String & String::operator=(const String &other)
{

        if (this == &other)
                return *this;

        delete [] m_data;

        m_data = new char[strlen(other.m_data)+1];

        strcpy(m_data, other.m_data);

        return *this;    // 返回的是 *this的引用,无需拷贝过程

}

String operator+(const String &s1, const String &s2)
{

        String temp;

        delete [] temp.m_data;    // temp.m_data是仅含‘\0’的字符串

        temp.m_data = new char[strlen(s1.m_data) + strlen(s2.m_data) +1];

        strcpy(temp.m_data, s1.m_data);

        strcat(temp.m_data, s2.m_data);

        return temp;

}
 

void String::print(void)
{
        printf("%s\n", m_data);
}

int main()
{
        String *p1 = new String("hello ");
        String *p2 = new String("world!");
        String *p3 = new String();
        *p3 = *p1 + *p2;
        p3->print();
        delete p3;
        delete p1;
        delete p2;

        exit(0);
}
 

用valgrind检测的命令如下:

valgrind --tool=memcheck ./t

输出:

==4610== Memcheck, a memory error detector
==4610== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==4610== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==4610== Command: ./t
==4610==
hello :in constructor
world!:in constructor
in constructor
in constructor
hello world!:in destructor
hello world!
hello world!:in destructor
hello :in destructor
world!:in destructor
==4610==
==4610== HEAP SUMMARY:
==4610==     in use at exit: 0 bytes in 0 blocks
==4610==   total heap usage: 9 allocs, 9 frees, 54 bytes allocated
==4610==
==4610== All heap blocks were freed -- no leaks are possible
==4610==
==4610== For counts of detected and suppressed errors, rerun with: -v
==4610== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 19 from 8)