Search code examples
c++mallocnew-operator

Should I always use the new operator in C++ instead of the malloc function?


struct A
{
 string st;
};

int main()
{
 A *a = (A *)malloc(sizeof(A));
 a->st = "print";

 cout << a->st;
 return 0;
}

When I use this way and it compiled successfully, but after that in runtime I got exception. So, I figure out one thing is A *a = new A; instead of A *a = (A *)malloc(sizeof(A));. Which way is better and without error for doing this type of things?

What should I do for runtime memory allocation?


Solution

  • malloc alone is outright wrong. malloc allocates memory, it does not create objects.

    new allocates memory and creates an object by calling the constructor.

    The "better" way is to not use either of the two when there is no reason to use them.

    int main() {
       A a;
       a.st = "print";
       cout << a.st;
    }
    

    A has only a single member of type std::string. std::string is already managing a dynamically allocated character string. There is no reason to dynamically allocate a std::string, and also no reason to use new to create an A.

    If you still need to dynamically allocate an object you should not use raw owning pointers. Your code leaks memory and there is no trivial fix for that (a delete at the end of main may never be reached when an exception is thrown). Use smart pointers when you do need to dynamically allocate an object.