如何安全地在C ++中为char *数组重新分配内存(它适用于CustomString类)

时间:2017-11-17 04:22:23

标签: c++ pointers memory-management

我认为我的老师主要是告诉我们分配记忆的错误方法......

但我不完全确定将更多内存安全地重新分配给指针的正确方法是什么。重新分配内存的目的是因为旧的内存分配不够大(例如,当执行前缀增量运算符重载时,如追加字符'X',可能你需要足够大的新分配来容纳endresult?)

问题:

  1. 所以我对于将内存重新分配给char * c_string的正确方法感到困惑,因为旧的内存分配不再足够大,我们需要更大的内存分配(这种情况发生在前缀中)增量运算符重载)?

  2. 我的现有代码在前缀增量运算符重载中是否有内存泄漏?

  3. 如何在Windows上的Visual Studio 2017中编写C ++时找到内存泄漏?

  4. 关于我的项目的基本信息: 目标是创建自己的CustomString类,并将char *指针作为CustomString类的私有实例变量。

    我已经创建了自己的CustomString类,我应该做一些运算符重载,例如加法运算符,前缀增量运算符。

    添加运算符的主要目的当然是字符串连接。使用前缀增量运算符,您只需在末尾添加一个字符“X”。

    我可以在这里发布我已经存在的代码的定义。

    CustomString.h

    #pragma once
    #include <iostream>
    #include <string.h>
    using namespace std;
    
    class CustomString
    {
        friend ostream &operator<<(ostream &out, const CustomString &reference);//OUTPUT OPERATOR OVERLOADED as friend function
    
    public:
        static const int MaxSize = 10;//classwide constant
        static int getNumberOfCustomStrings();
    
        CustomString(const char *namepointer="");// constructor
        //CustomString(char * pointer);//constructor w/parameters
        ~CustomString();//destructor
        CustomString(const CustomString &stringref);    //copy constructor w/dynamic datamember
        operator const char*() const; // IMPLICIT CONVERSION operator overloaded
    
    
         CustomString operator+( const CustomString &addedpart) const;  // PLUS OPERATOR OVERLOADED implemented as string concatenate
        const CustomString& operator=(const CustomString &ref); //ASSIGNMENT OPERATOR OVERLOADED works for dynamic strings as well
        const CustomString &operator++();//PREINCREMENT OPERATOR OVERLOADED
        CustomString operator++(int);//POSTINCREMENT OPERATOR OVERLOADEd
        char& operator[](int i) const;// INDEXING OPERATOR OVERLOADED
    
    private:
        char * c_string;
        void list();
        static int numberOfCustomStrings;
    };
    

    来自CustomString.cpp,这是代码的前缀增量部分

    const CustomString & CustomString::operator++()// PREFIX INCREMENT OVERLOADED, adds an 'X' character into the dynamic instance variable(char*c_string)
    {
    
        if (  strlen(c_string) == (MaxSize-1)   ) {
            cout << "error cannot increment any further" << endl;
            return *this;
        }
        else {
            int oldlength = strlen(c_string) +1;
            char*newdata;
            newdata = new char[ oldlength+1  ]; //it has to be one char bigger allocation bevause one "X" soon will be added
            strcpy_s(newdata, oldlength+1, c_string);//put the old data into new allocation as the baseword
            newdata[oldlength-1] = 'X';
            newdata[oldlength] = '\0';
            delete c_string;//free the old memory
            c_string = newdata; //give  the new allocation to the dynamic instance variable
            return *this;
    
        }
    
    }
    

    我相信我已经正确地执行了析构函数,构造函数和复制构造函数,但我也可以给出他们的代码

    CustomString.cpp的构造函数

    CustomString::CustomString(const char *pointer)// constructor
    {
        if(   (strlen(pointer)+1) <=MaxSize   ){
        c_string = new char[strlen(pointer) + 1];
        strcpy_s(c_string, (strlen(pointer) + 1), pointer);
        numberOfCustomStrings++;
        }
        else {
            c_string = new char[MaxSize];
            //printf("char at last index was == %c \n", c_string[MaxSize-1]);
            int j = 0;
            for (j = 0; j <= (MaxSize-2); j++) {
                c_string[j] = pointer[j];
            }
            //printf("the last truechar was %c \n",pointer[MaxSize-2]);
            c_string[MaxSize - 1] = '\0';
            //printf("the last char was %c\n", pointer[MaxSize-1]);
            numberOfCustomStrings++;
        }
    
    }
    

    这是CustomString.cpp的复制构造函数

    CustomString::CustomString(const CustomString &ref)     //copy-constructor w/dynamic data member.
    {
        c_string = new char[strlen(ref.c_string) + 1];  
        strcpy_s(c_string, strlen(ref.c_string) + 1, ref.c_string);
        numberOfCustomStrings++;
    }
    

    这是CustomString.cpp

    中的析构函数
    CustomString::~CustomString()   // destructor
    {
        delete c_string;  
        cout << "destructor called!" << endl;
        numberOfCustomStrings--;
    }
    

1 个答案:

答案 0 :(得分:0)

代码:

char *a = new char;
delete a;

char *array = new char[100];
delete [] array;

您可以使用可视检漏仪找到一条线