Search code examples
c++memory-managementmemory-leaksnew-operatordelete-operator

C++ memory management. What is wrong with this code?


I was asked this in an interview:
"In terms of memory management in C++, state everything that is wrong with this code?"

int main(){
        for(int i = 0; i<10; i++){
        Foo foo = new Foo();
        delete foo; }
        }



class Foo{

    foo(){
        string x = new string;
        }
    }

I am new to C++ and OOP, so I was a bit stuck. Help?


Solution

  • It won't compile for starters. In string x = new string; the types don't match. You are assigning a string* to a string variable. You need string* x = new string;.

    Also foo isn't a constructor for Foo as the case isn't the same so you will have a missing return type error.

    Then you are leaking a string object every time you construct a new object as delete is never called on the newed object.