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;
}
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
.
在代码末尾delete arr
将处理内存泄漏。
Ownership of arr
is not passed to s
, it copies arr
to s
's internal buffer. You should free memory with delete
operator
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.
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.