Exception
Exception

Reputation: 307

Deallocating Dynamic Memory

I recently did a school homework assignment and lost points, in the comment the grader said that I didn't deallocate the pointers correctly. Below is the code I sent, I would just like to know how it would look to deallocate the pointers correctly?

/*Student: Daniel
 *Purpose: To reverse a string input using
 *pointers.
 */
#include <iostream>
#include <cstring>
#include <string>
using namespace std;

int main() {
    string input;
    char *head = new char, *tail = new char;
    char temp;
    //Get the string from the user that will be reversed
    cout << "Enter in a string that you want reversed: ";
    getline(cin, input);
    //Create and copy the string into a character array
    char arr[input.length()];
    strcpy(arr, input.c_str());
    //Set the points of head/tail to the front/back of array, respectably
    head = &arr[0]; tail = &arr[input.length()-1];
    for(int i=0; i<input.length()/2; i++) {
        temp = *(tail);
        *tail = *head;
        *head = temp;
        tail --; head ++;
    }
    for(int i=0; i<input.length(); i++) {
        cout << arr[i];
    }
    //********MY PROBLEM AREA*************
    delete head; delete tail;
    head = NULL; tail = NULL;
    return 0;
}

Upvotes: 1

Views: 126

Answers (1)

NG.
NG.

Reputation: 22904

So take a look here...

char *head = new char, *tail = new char;

And then...

//Set the points of head/tail to the front/back of array, respectably
head = &arr[0]; tail = &arr[input.length()-1];

You reassigned what head and tailpoint to, so you're not actually deleting the right things when you call delete. In fact, I'm surprised you don't crash.

Really you can probably just do:

char *head = NULL; char* tail = NULL;

and then not delete anything since you won't have anything dynamic.

Upvotes: 7

Related Questions