3

Here I have an array of dynamically-allocated c-strings.

  • What is the proper way to free such an array?

  • It is necessary to individually free each element of A, as code below?

Thank you.

#include <string.h>
int main()
{
    const char** A = new const char*[3];
    A[0] = (const char*)memcpy(new char[5], "str0", 5);
    A[1] = (const char*)memcpy(new char[5], "str1", 5);
    A[2] = (const char*)memcpy(new char[5], "str2", 5);

    // Is this the proper way to free everything?
    for (int i = 0; i < 3; ++i)
        delete[] A[i];
    delete[] A;
}
12
  • 7
    Why not use a std::vector<std::string> and leave the memory management to the standard library? Commented Nov 29, 2016 at 20:38
  • 1
    Just use a vector<string>. Commented Nov 29, 2016 at 20:39
  • 2
    #include <string> -- Yet you failed to use std::string. This is the header that defines std::string, std::wstring, etc. I don't know what else you expected when you included this header. Commented Nov 29, 2016 at 20:41
  • 1
    c-strings are faster than library strings -- Nothing stopped them from writing a simple C++ class that handles strings. If they were competent, it shouldn't have taken more than an hour. Commented Nov 29, 2016 at 20:46
  • 1
    @SamShen Yeah there should almost be no difference between std::string and doing it yourself. When you get the added benefits of all the built in functions, memory safety and ease of use it is worth using std::string. About the only time not to is if you know you have/need a fixed sized buffer. Commented Nov 29, 2016 at 20:47

1 Answer 1

6

Yes. Everything is OK as long as every new ...[] is matched with a delete[] ....

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.