c++ - 在 C++ 中调整数组大小时如何修复错误?
问题描述
我有一个小程序,它返回一行输入的字符:
#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;
}
但这给了我一个错误:
失败的测试#1。在抛出“std::logic_error”what() 实例后调用运行时错误终止:发生内存泄漏或双重分配已中止(核心转储)
我不完全明白问题出在哪里,因为我是 C++ 新手。如何解决问题?
解决方案
这里有一个问题:m = resize(str, size, ++size);
. 未指定函数参数的求值顺序,因此允许编译器size
在将 的值size
作为第二个参数传递之前递增。将代码重写为m = resize(str, size, size+1); ++size;
.
推荐阅读
- java - 如何在 Eclipse 中使用启动配置作为模板
- python - 在 Python 中从 BMP 文件中提取图像的小区域
- php - CKFinder - 致命错误:具有类类型提示的参数的默认值只能为 NULL
- mysql - MySQL View 数据类型问题?
- unit-testing - Puppeteer 和 Electron 在使用它来测试应用程序的客户端方面有什么区别
- javascript - 突出显示将 id 选择器传递给函数的特定 select2
- c# - 在 Blazor 中每两秒显示一次字符串列表中的项目
- python - 如何设置初始条件以获得轨迹作为运动方程的解?
- python - 如何调整窗口大小以填充全屏高度但指定屏幕宽度?
- php - 如何通过选择课程 ID 来选择特定课程并将用户所有选定的课程与同一行连接起来