c++ new/delete and char *

前端 未结 8 930
醉梦人生
醉梦人生 2021-02-02 11:50

Can anyone help me, why I\'m getting an error message while trying to free the allocated memory: Heap corruption detected. CTR detected the application wrote the memory after en

8条回答
  •  滥情空心
    2021-02-02 12:20

    All answers so far have addressed either the first or the second allocation. To sum up, there are two changes you must make:

    char *s1 = new char [strlen(s) + 1];
    ...
    char *s = new char [5 + 1];
    

    In both cases, you must allocate enough space for the string plus one byte for the terminating '\0'.

    As others already pointed out, with c++ it's easier and safer to use std::string. No fuss with allocation and release of memory or paying attention to '\0' bytes:

    std::string ff (const std::string &s){
        std::string s1(s);
        // do something else with s1
        return s1;
    }
    
    int main(int argc, char* argv[])
    {
        std::string s("hello");
        std::string s2 = ff(s);
        return 0;
    }
    

    and if it's just copying the string:

    std::string s("hello");
    std::string s2(s);
    

提交回复
热议问题