Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freeing array of c-strings

Tags:

c++

c-strings

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;
}
like image 967
kgf3JfUtW Avatar asked Feb 24 '26 05:02

kgf3JfUtW


1 Answers

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

like image 128
Gavin Haynes Avatar answered Feb 26 '26 19:02

Gavin Haynes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!