c++ - 字符串复制函数产生 `pointer being freed was not allocated`

标签 c++ string memory-management deep-copy

我有以下功能:

void stringcopy(char * to, char const * const from)
{
    int size = 1;
    while (from[size] != '\0') { ++size; }

    if (to != 0) { delete [] to; }
    to = new char[size];

    for (int i = 0; i < size; i++) { to[i] = from[i]; }
}

顾名思义,它使用动态分配复制字符串。


我不认为我使用它的方式应该重要(因为我正在努力使这个功能健壮),但这里有一些例子:

CD::CD(char * s1, char * s2, int n, double x)
{
    stringcopy(performers, s1);
    stringcopy(label, s2);
    selections = n;
    playtime = x;
}

CD::CD(const CD & d)
{
    stringcopy(performers, d.performers);
    stringcopy(label, d.label);
    selections = d.selections;
    playtime = d.playtime;
}

等等


不幸的是,当我使用该函数时,我收到以下错误消息:未分配正在释放的指针

我假设它发生了 do to if (to != 0) { delete [] to;


为什么这条线不能防止释放未分配的内存?

最佳答案

你在这里做什么

if (to != 0) { delete [] to; }
to = new char[size];

正在释放本地 to 变量指向的内存,重新分配它并将字符串存储在那里。

这个新的本地内存地址(我们称它为 to1)永远不会暴露给外界,因为它不是从函数返回的。函数 get 是 to 地址的拷贝。为了解决这个问题,您需要将 to 设为双指针。或对指针的引用。

关于c++ - 字符串复制函数产生 `pointer being freed was not allocated`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40249443/

相关文章:

c++ - 如何从 C++ 中的网络摄像头读取输入?

C++ 递归与数组

string - 如何在ActionScript中将字符串转换为 boolean 值?

ruby - 我可以使用字符串作为可执行代码行的一部分吗?

swift - 在 Swift 中,声明变量并赋值是一种好习惯吗?

windows - 进程的默认堆

Android:浅堆和保留堆有什么区别

c++ - 从构造函数初始化列表中传递它

php - 数组到字符串到数组的转换

c++ - g++ 的 std::list::sort 是否使迭代器无效?