search

Home  >  Q&A  >  body text

C++ vector<char *>释放空间失败 ?

PHP中文网PHP中文网2803 days ago640

reply all(3)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:26:55

    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

    reply
    0
  • ringa_lee

    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`
    

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:26:55

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

    reply
    0
  • Cancelreply