伊谢尔伦2017-04-17 13:26:55
At the C++ level, your code is not wrong, it will also free the memory. free
However, the runtime of C/C++, that is, libc, will not really free this memory. Because if there is malloc later, he will have to apply for memory from the operating system, so it is better to keep it himself.
Currently, all libc will cache the memory by itself to increase the speed of application and release.
The C++ code you wrote is too bad. If you continue to write it like this in the future, you will suffer a lot
ringa_lee2017-04-17 13:26:55
What environment does the questioner use? I use MAC + g++ and there is no problem.
`tianbing:Temp tianbing$ cat test.cpp
#include<iostream>
#include<vector>
using namespace std;
int main(int argc, char ** argv){
vector<char *> strVec;
char *wordTmp = new char[strlen("abc")];
strcpy(wordTmp, "abc");
strVec.push_back(wordTmp);
delete[] strVec[0];
cout << "free sucessfully" << endl;
return 0;
}
tianbing:Temp tianbing$ g++ test.cpp -o test
tianbing:Temp tianbing$ ./test
free sucessfully`
PHP中文网2017-04-17 13:26:55
In this case, if possible, it is recommended to use smart pointers and STL containers.