1

对于与动态内存和复制构造函数有关的简单分配,我的教授已经分配给我们一个简单的分配,但是在第二次发生时我得到了一个错误delete []

头文件:

class Stream {
    int len;
    char *hold;
    char* newmem(int);
public:
    Stream ();
    Stream (int);
    Stream(const char *);
    ~Stream ( );
    void operator=(const Stream &);
    Stream(const Stream &);
    friend void show(Stream);
    void operator<<(const char*);
};

它应该相当简单。这是我的代码:

#include <iostream>
#include <new>
#include <cstring>
using namespace std;
#include "stream.h"

char* Stream::newmem(int x) {
    char * tmp;
    try {
        tmp = new char[x];
    }
    catch(std::bad_alloc) {
        tmp = NULL;
    }
    if(tmp)
        cout << "newmem:  " << (void *) tmp << endl;
    return tmp;
}

Stream::Stream ( ) {
    len = 1000;
    hold = newmem(len);
    if (hold)
        strcpy (hold, "");
}

Stream::Stream(int n) {
    len = n;
    hold = newmem(len);
    if (hold)
        strcpy (hold,"");
}

Stream::Stream(const char * dat) {
    len = strlen(dat) +1;
    hold = newmem(len);
    if (hold)
        strcpy(hold,dat);
}

Stream::Stream(const Stream &from) {
    cout << "in the copy constructor, allocating new memory..." << endl;
    cout << "original pointer address is: " << (void *) from.hold << endl;
    cin.get( );

    len=from.len;
    hold=newmem(len +1);
    cout << "new pointer address is: " << (void *) hold << endl;
    cin.get( );

    if(hold)
        strcpy (hold,from.hold);
}

Stream::~Stream ( ) {
    cout << "destruct:  " << (void *) hold << endl;
    cin.get( );
    if (hold)
        delete [] hold;
}

void Stream::operator= (const Stream &from) {
    if(hold)
        delete [ ] hold;
    len = from.len;
    hold=newmem(len +1);
    if (hold)
        strcpy(hold,from.hold);
}

void show (Stream prt) {
    cout << "String is: " << prt.hold << endl << "Length is: " << prt.len << endl;
}

void Stream::operator<< (const char *data) {
    int dlen = strlen(data);
    for (int i=0 ; i<=len && i<=dlen ; i++) {
        hold[i] = data[i];
    }
}

int main( ) {
   char data[ ] = "Growing up it all seems so one-sided;"
                  "Opinions all provided;"
                  "The future pre-decided;"
                  "Detached and subdivided;"
                  "In the mass production zone!"
                  "-Neil Peart- \"Subdivisions\"";

   Stream x1, x2(25), x3;
   x1 << data;
   x2 << data;
   show(x1);
   show(x2);

   x3 = x2;
   show(x3);

   return 0;
}

和我的输出/错误:

在复制构造函数中,分配新内存...
原始指针地址为:0x804c008

新指针地址为:0x804c808

弦是:长大这一切似乎如此片面;意见全都提供;未来已定;分离和细分;在量产区!-Neil Peart-细分”
长度为:1000
破坏:0x804c808


在复制构造函数中,分配新内存...
原始指针地址为:0x804c3f8

新指针地址为:0x804c808

字符串是:长大了这一切似乎都是如此
长度为:25
破坏:0x804c808

*** 检测到 glibc *** a.out:free():无效指针:0x0804c808 ***
4

2 回答 2

4

中的 for 循环operator<<两个错误:

for (int i=0 ; i<=len

允许i==len,但唯一有效的索引hold0..(len-1)。所以,你可以在最后写一个。

其次,正如 thiton 指出的那样,\0即使有空间,它也不会复制终止符。


正确的实现可能如下所示:

void Stream::operator<< (const char *data) {
    int source_len = strlen(data);
    int copy_len = min(source_len, len-1); // allow for terminator

    for (int i=0; i<copy_len; i++) {
        hold[i] = data[i];
    }
    hold[copy_len] = '\0';
}

尽管最好简单地使用strncpy.


请注意,使用半开(或过去一个)范围的习惯用法不仅在直接数组索引中是标准的,而且在 C++ 迭代器中也是标准的。所以,你应该总是期望看到

for (i=0; i<n; ++i) {

或者

for (i = begin; i != end; ++i) {

并且通常应该将像您这样的封闭式循环视为值得进一步调查的气味。

于 2013-03-20T21:15:21.553 回答
1

首先是一点自助建议:捕获内存访问错误的最重要工具是valgrind. 在您的程序上运行它,每次您尝试访问未分配或未初始化的内存时都会收到警告。它不能替代知识,而是下一个最好的东西。

虽然我得到的输出与你得到的不同,但错误似乎在这里相互作用:

  1. operator<<范围检查中有一个错误。它写了一个字节太多(hold[len])。
  2. operator<<永远不会写入终止的空字节。这两个错误都是由 调用的x2 << data
  3. 当复制构造函数尝试从 复制字符串时x2strcpy找不到终止的空字节,并且都在 结尾处读取并在结尾处x2.hold写入x3.hold。后者有可能造成无限的损坏,并可能导致您的错误。

每当您处理 C 字符串时,请务必确保正确终止。固定版本是:

void Stream::operator<< (const char *data) {
    int dlen = strlen(data);
    hold[len-1] = 0;
    for (int i=0 ; i < len-1 && i <= dlen ; i++) {
         hold[i] = data[i];
    }
}

或者,使用 std 库:

void Stream::operator<< (const char *data) {
    strncpy(hold, data, len);
    hold[len-1] = 0;
}
于 2013-03-20T21:15:38.087 回答