Memory leak C++

后端 未结 10 563
野趣味
野趣味 2021-02-02 06:02

I just wrote a code in C++ which does some string manipulation, but when I ran valgrind over, it shows some possible memory leaks. Debugging the code to granular level I wrote a

10条回答
  •  死守一世寂寞
    2021-02-02 07:00

    This also raise another question for me, is such a code harmful?

    #include
    int main()
    {
            char *p=(char *)malloc(sizeof(char)*1000);
            exit(0);
    }
    

    It's not harmful on modern operating systems, because they will close all resources owned by a process automatically when the process ends.

    However, it's still bad practice, and might lead to subtle and hard to find errors when, over several years of maintenance, the code slowly changes until, on day, this does become harmful. I have worked in projects where some of the code was a decade old and I have learned a few lessons doing so, some of them rather harsh. Therefore, I would avoid writing such code, even if it currently doesn't pose a problem.

提交回复
热议问题