我有以下功能:
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/