我有一个返回一行输入字符的小程序:
#include <iostream>
char *resize(const char *str, unsigned size, unsigned new_size);
char *resize(const char *str, unsigned size, unsigned new_size)
{
char * m = new char[new_size];
for (int i = 0; i < size && i < new_size; ++i) {
m[i] = str[i];
}
delete [] str;
return m;
}
char *getline()
{
char ch;
std::cin >> ch;
int size = 1;
char * str = new char[size];
char * m;
while (std::cin.get(ch) && ch != '\n') {
str[size-1] = ch;
m = resize(str, size, ++size);
m[size] = '\0';
}
return m;
}
但它给了我一个错误:
Failed test #1. Runtime error terminate called after throwing an instance of 'std::logic_error' what(): Memory leak or double allocation occured Aborted (core dumped)
我不完全明白问题出在哪里,因为我是 C++ 的新手。如何解决问题?
最佳答案
这里有一个问题:m = resize(str, size,++size);
。函数参数的计算顺序未指定,因此允许编译器在将 size
的值作为第二个参数传递之前递增 size
。将代码重写为 m = resize(str, size, size+1);++大小;
。
关于c++ - 在 C++ 中调整数组大小时如何修复错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57043811/