释放动态内存

时间:2013-11-10 02:24:02

标签: c++ pointers memory

我最近做了一个学校的家庭作业和失分,在评论中,评分者说我没有正确地释放指针。 下面是我发送的代码,我想知道如何正确释放指针?

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

1 个答案:

答案 0 :(得分:7)

所以看看这里......

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

然后......

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

您重新分配了headtail指向的内容,因此当您调用delete时,实际上并没有删除正确的内容。事实上,我很惊讶你不会崩溃。

你真的可以这样做:

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

然后不删除任何内容,因为你没有任何动态。