C++ 指向存储乱码的新内存的指针

标签 c++ pointers dynamic char

我有一个接受字符数组的类。我意识到 std::string 更适合处理字符串,但这是了解指针和分配动态内存的练习。 我遇到的问题是重载的加法运算符。我将新内存分配给连接的两个 char 数组的大小,加上一个终止空字符。当我在 for 循环上放置断点时,我可以看到程序正在迭代左手操作数指针(p),然后迭代右手操作数指针(q),但各个字符没有存储到 temp_str。

我对 C++ 相当陌生,所以我确信我错过了一些关于指针和/或动态内存的基本知识。任何帮助/建议将不胜感激。谢谢。

#include <iostream>
#include <cstring>
using std::cout;
using std::endl;

class CStr
{
private:
    int m_length;
    char* m_pstr;

public:
    // Constructor
    CStr (const char* s = "Default String")
    {
        cout << "Constructor called\n";
        m_length = strlen(s) + 1;           // Store the length of the string
        m_pstr = new char[m_length];        // Allocate space for the string
        strcpy_s(m_pstr,m_length,s);        // Copy string to memory
    }

    // Copy constructor
    CStr (const CStr& aStr)
    {
        cout << "Copy constructor called\n";
        m_length = aStr.m_length;                   // Get length of the object to be copied
        m_pstr = new char [m_length];               // Allocate space for the string
        strcpy_s(m_pstr, m_length, aStr.m_pstr);    // Copy string to memory
    }           

    // Assignment operator
    CStr& operator=(const CStr& aStr)
    {
        cout << "Assignment operator called\n";

        if(this == &aStr)                               // Check addresses, if equal
        return *this;                               // return the 1st operand

        m_length = aStr.m_length;                           // Get length of the rhs operand

        delete [] m_pstr;                               // Release memory for the lhs operand
        m_pstr = new char[m_length];                        // Allocate space for the string

        strcpy_s(m_pstr, m_length, aStr.m_pstr);        // Copy rhs operand string to the lhs operand

        return *this;                                       // Return a reference to the lhs operand
    }  

    // Addition operator
    CStr operator+(const CStr& aStr) const
    {
        cout << "Addition operator called\n";

        // get the lengths of the strings
        size_t rhs_length = strlen(aStr.m_pstr);                    // length of rhs operand
        size_t lhs_length = strlen(this->m_pstr);                   // length of lhs operand

        char* temp_str = new char[lhs_length + rhs_length + 1];     // Allocate memory to hold concatenated string
                                                                    // plus terminating null character
        char* p = this->m_pstr;
        char* q = aStr.m_pstr;

        for (p; *p!=0; p++)             // Increment lhs string pointer 
            *temp_str++ = *p;           // Store character

        for (q; *q!=0; q++)             // Increment rhs string pointer
            *temp_str++ = *q;           // Store character

        *temp_str++ = '\0';             // Null character at the end

        return CStr(temp_str);
    }

    // Destructor
    ~CStr ()
    {
        cout << Print() << " has been destroyed\n";
        delete [] m_pstr;                               // Free memory assigned to the pointer
    }

    // Print function
    char* Print() const
    {
        return m_pstr;
    }
};

int main()
{
    CStr s1("foo");
    CStr s2("bar");

    CStr s3 = s1 + s2;
}

最佳答案

在复制操作中,您将执行 temp_str++ 直到 temp_str 指向您分配的数组之外,因此返回的 CStr(temp_str)超出它的点也是如此。

您可以通过在复制循环内使用单独的指针,或在返回之前从 temp_str 中减去存储的字符数来轻松解决此问题。

关于C++ 指向存储乱码的新内存的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18211102/

相关文章:

c++ - 为什么 "possible lack of precision"不是编译器错误?

c - 仅包含根的二叉搜索树,删除会导致打印无限个地址

C++ 指针损坏?

c# - 如何在c#中使用动态语法?

c++ - 这是初始化 vector 的坏方法吗?

c++ - 共享内存中的映射 : Boost. 由于未满足 date_time 依赖性,进程间演示失败

C++ 更改字符串函数中的小写字母(再次......)

c++ - C++ 中的动态数组大小

Python拦截方法调用

c++ - 双免腐败