1

When i run valgrind on below program, it reports memory leak. Can you please explain the cause?

#include <string>
#include <iostream>

using namespace std;

int main()
{
    char * arr = (char *) ::operator new(sizeof(char));
    string s = arr;

    return 0;
}
  1. What exactly happens on line string s = arr? does it make a copy of arr?
2
  • 4
    why would you even write that code?! @Aneri: Arr you a pirate? ;-) Commented Mar 13, 2013 at 16:02
  • std::string will not magically free your array Commented Mar 13, 2013 at 16:02

5 Answers 5

5

valgrind is right. You call new and don't call delete, hence you have a memory leak.

When you assign arr to s, the latter doesn't take ownership of the former; instead, it makes a copy. It is still your responsibility to free arr.

Sign up to request clarification or add additional context in comments.

Comments

1

Ownership of arr is not passed to s, it copies arr to s's internal buffer. You should free memory with delete operator

Comments

1

I think you assumed string will take the ownership of arr and it's responsible for delete the arr. BUT IT IS WRONG.

string s = arr;

Just copies characters from arr until reaching to \0. So, you should delete arr yourself.

Comments

1

delete arr at end of your code will handle memory leak.

Comments

0

The new[] operator in C++ allocates memory dynamically. All such memory must be freed manually, by the programmer. This is done with the delete[] operator. If you don't delete memory which you allocated with new, you have created a memory leak.

More information on that topic can be found in this C++ FAQ.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.