C++ vector<char *>释放空间失败 ?
PHP中文网
PHP中文网 2017-04-17 13:24:55
0
3
626
PHP中文网
PHP中文网

认证高级PHP讲师

reply all(3)
伊谢尔伦

At the C++ level, your code is not wrong, it will also free the memory. freeHowever, 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.

PS:

The C++ code you wrote is too bad. If you continue to write it like this in the future, you will suffer a lot

左手右手慢动作

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`
洪涛

In this case, if possible, it is recommended to use smart pointers and STL containers.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template