asked 15.9k views
1 vote
Which statement properly frees the dynamically allocated array below? Musketeer* ∗ musketeers = new Musketeer[8]; a. delete musketeers; b. delete[] musketeers; c. musketeers->delete; d. for (i=0;i<8;i++){ delete musketeers[i]; \}

asked
User Levenal
by
7.6k points

1 Answer

5 votes

Answer:

The statement that properly frees the dynamically allocated array of Musketeer objects is b. delete[] musketeers;.

Step-by-step explanation:

The statement `new Musketeer[8]` dynamically allocates an array of 8 Musketeer objects and returns a pointer to the first element of the array. To free this memory and prevent a memory leak, we must use the `delete[]` operator followed by the name of the pointer to the array.

Therefore, the correct statement to free the dynamically allocated array is `delete[] musketeers;`. This will properly deallocate the memory that was allocated for the array of Musketeer objects. Option a (`delete musketeers;`) would only free the memory for the first object in the array and not the entire array, resulting in a memory leak. Option c (`musketeers->delete;`) is not a valid way to free memory in C++, and option d (`for (i=0;i<8;i++){ delete musketeers[i]; }`) is incorrect because the objects in the array were not created using `new` and should not be deleted individually.

answered
User Zeflex
by
8.0k points