c++ - 释放动态内存

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

最佳答案

所以看看这里...

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;

然后不要删除任何东西,因为你不会有任何动态。

关于c++ - 释放动态内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19885555/

相关文章:

c++ - 为什么在 C 和 C++ 中动态分配的对象是未命名的?

memory - Jmapping 的基础知识?

caching - 为什么 RAM 不如寄存器/高速缓存那么快?

c - while(*pointer) 在 C 中合法吗?

c - 函数接收一个指向 double 的指针,分配内存并填充结果 double 组

c - 应用程序无缘无故地被杀死。怀疑 BSS 高。如何调试呢?

c++ - 计算距对象起点的距离时,_ATL_PACKING 常量有什么用?

c++ - Eigen::MatrixXd 到 flann::Matrix<double> 转换

c++ - 为什么在将 extern const (int) 包含在头文件中时不需要为其赋值?在 C++ 中

c++ - 使用 Boost Spirit Qi 解析包含文字的字符串