[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: [ProgSoc] simple c++ q (delete)



Title: RE: [ProgSoc] simple c++ q (delete)

>       delete [] a;
>       delete a;

> .. and that looks pretty dodgy. I dont know whether it works either =)

Eeek! Don't! With the second delete you are deleting a pointer that was not allocated with new which produces "undefined behaviour" (read: crash).

If the members of the array are pointers, delete each with the for loop and then, if the array itself was dynamically allocated, "delete []" it. Both steps are required. E.g.:

int i;
const int num_strings = 10;
const int string_length = 20;
char **s;

s = new char*[length]; // Allocate the array
for(i = 0; i < num_strings; i++)
        s[i] = new char[string_length];
                // Allocate the individual array element

// Use the strings

for(i = 0; i < num_strings; i++)
        delete s[i];  // Delete the individual array element
delete [] s; // Delete the array itself


Anthony Langsworth
Software Developer
Computing Edge
mailto:anthonyl@nospam.computingedge.com.au