Does strcpy'ing a string into into a larger char array cause a memory leak?
Hey all, just wondering whether the following would cause a memory leak?
开发者_Python百科char* a = "abcd"
char* b = new char[80];
strcpy(b, a);
delete[] b;
Will it delete the whole block of 80 or just the 4 characters copied into it by strcpy? Thanks!
You allocated 80 bytes into b
, so delete[]
will free 80 bytes. What you did with the array in the meantime is irrelevant.
(Unless, of course, you corrupted the heap, in which case delete[]
will probably crash.)
EDIT: As others have pointed out, since b
is an array, you need to use delete[] b;
instead of delete b;
. Some implementations might let you get away with that, but others won't, and it would still be wrong.
A memory leak is when you don't free memory. Just because you allocated more than you need doesn't mean it a memory leak. What you do with your memory is up to you.
Though that should 1) be delete [] b;
, or you get undefined behavior, and 2) Be a std::string
or std::vector
, so you don't both manage and use a resource.
The allocation system will take care of remembering how long the allocations are. The contents don't matter at all.
However, you do need to call the right delete operator. In this case since you allocated new[] you need to delete[].
The last line should be:
delete[] b;
If you allocate one item use delete, if you're allocating an array use delete[].
Since this is tagged C++, here's the C++ version - good to understand memory management via new/delete
, but better to avoid doing it by hand using RAII.
#include <string>
#include <iostream>
using namespace std;
int main()
{
string a("abcd");
string aCopy(a);
cout << aCopy << endl;
const char* b(aCopy.c_str());
cout << b << endl;
}
精彩评论