1

When I create a class, include a pointer in it, and create an object in automatic storage, should I include a destructor in the class? (is it necessary to free the space in the memory?) Example:

class Node{
    char *Name;
    int age;
    Node(char *n = 0, int a = 0) {
        name = strdup(n);
        age = a;
    }
    ~Node(){
        if (name != 0)
            delete(name);
    }
}

Node node1("Roger",20);

3 Answers3

4

is it necessary to free the space in the memory?

Yes, it's essential to avoid memory leaks.

Anyway you must use free(name); in your example, since strdup() is a pure C function, and uses the malloc() function to allocate the memory for the copy returned.


Also, you should avoid managing raw pointers yourself in C++. Either use smart pointers, or standard C++ containers, or for your specific case simply std::string.

Raw pointers don't go well with, respectively complicate, implementing the Rule of Three (5/zero).

If you have something allocated from a C-style interface, you can always use a smart pointer, and provide a custom deleter function, that actually uses the appropriate free() call.

Community
  • 1
  • 1
πάντα ῥεῖ
  • 85,314
  • 13
  • 111
  • 183
  • @downvoters care to explain what's wrong with my answer here please? I can't see anything wrong? I'd suppose it was just a _tactical reason_ or what? – πάντα ῥεῖ Sep 28 '15 at 18:23
2

If your class has a pointer that points to memory that is allocated with new \ new[] \ malloc() then you need to implement the Rule of Three

That said, instead of using a raw char * and manual memory management, use a std::string instead. you can still get a const char* out of it if you need it for other functions but it fully self managed container. With it you would not need to provide a copy constructor or destructor as the default ones provided by the compiler will work.

Community
  • 1
  • 1
NathanOliver
  • 161,918
  • 27
  • 262
  • 366
1

Yes, this is mandatory to avoid memory leaks. It doesn't matter if you are using a class or something else. It's important what strdup says. But you must not use delete, instead use free. The memory in strdup is created by using malloc, not new.

http://pubs.opengroup.org/onlinepubs/009695399/functions/strdup.html

strdup - duplicate a string

The returned pointer can be passed to free(). A null pointer is returned if the new string cannot be created.

P.S. Don't miss const in your declaration of char *n, otherwise the caller might expect the string is modified and a simple-string literal cannot be passed without a warning.

P.S.2: Prefer using nullptr instead of 0. This has been discussed several times on SO.

Community
  • 1
  • 1
HelloWorld
  • 2,733
  • 2
  • 25
  • 54