简体   繁体   中英

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;
}

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 tail point 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM