【发布时间】:2017-03-20 13:13:50
【问题描述】:
我试图创建一个 C++ 程序,允许用户输入他/她喜欢多少个字符(只要内存可以接受),一旦他们按下回车键(ASCII 码:13),程序打印出用户输入的整个字符串。
但由于某种原因,即使程序输入的字符数量与您输入的一样多,它也不会打印出用户输入的整个字符串......好吧,它只是停止运行,当我查看我的 Windows 资源监视器显示程序发生内存泄漏,几秒钟后就会清理干净,但我真的很想知道我的程序出了什么问题。
提前致谢
这是我的完整源代码:
#include<iostream.h>
#include<conio.h>
int main()
{
int ctr = 0, n = 10, counter = 0;
char *stloc = NULL, *ptr = NULL, *cptr = NULL; // creating a NULL pointer
ptr = new char[n]; // get an array of 10 bytes allocated in heap memory
while((int)(*ptr) != 13) // Take input till Enter Key is pressed
{
if(counter == (n+ctr-1)) // Check if array overflow is going to happen
{
ctr+=2; // add two to ctr so that an extra 2 byte space is created in the new char array for a character and '\0'
cptr = new char[n+ctr];
strcpy(cptr,ptr);
delete [] ptr;
ptr = cptr;
stloc = ptr;
}
*ptr = getche();
ptr++;
counter++;
}
*ptr = '\0';
cout << endl << stloc;
delete [] ptr;
system("pause");
}
【问题讨论】:
-
你从哪里得到用户的输入?另外为什么不使用
std::string?您的整个程序可以替换为std::string input; std::getline(std::cin, input); -
由于您正在执行指针运算以使用
ptr作为迭代器,因此调用delete ptr是一个非常糟糕的主意。而且由于它不是字符串的开头,因此调用strcpy(cptr, ptr)来传输内存内容也是一个坏主意。即便如此,在每次调整大小并覆盖内容后,您仍将ptr重置为字符串的开头。 -
C 运行时库将
Return 转换为换行符 ('\n'),其 ASCII 码是 10 而不是 13...此时您测试 *ptr , ptr 指向一个未初始化的值!在第一次运行时,什么都没有读过,接下来,你只是增加了 ptr...除非你有特殊要求,否则停止使用 conio 并遵循 C++ 教程。
标签: c++ memory-management dynamic memory-leaks