为什么这个程序崩溃
Why does this program crashes?
#include<iostream>
#include <cstring>
using namespace std;
typedef struct {char *str;}String;
int main(){
String name,add;
cout<<"Name: ";
cin>>name.str;
cout<<"ntadd: ";
cin>>add.str;
cout<<"ntName:"<<name.str;
cout<<"nt Add:"<<add.str;
return 0;
}
输入成功,然后程序崩溃。
显示错误:停止工作
不,不,不,只用std::string
!更易于使用,也更容易理解!
#include<iostream>
#include <string>
using namespace std;
int main(){
string name,add;
cout<<"Name: ";
getline(cin, name); // A name probably has more than 1 word
cout<<"ntadd: ";
cin>>add;
cout<<"ntName:"<<name;
cout<<"nt Add:"<<add;
return 0;
}
就原始代码的问题而言,您没有为char*
分配任何内存,并且正在读取不属于您的内存。
str
是结构及其pointer
类型的成员,在执行name.str;
时它没有任何valid memory
这就是它在运行时崩溃的原因。
首先为str
分配内存
name.str = new char [SIZE]; /* SIZE is the no of bytes you want to allocate */
工作完成后,通过使用delete
释放内存以避免内存泄漏。
delete [] name.str;
相关文章:
- 提升 ASIO Async_receive崩溃程序
- 类指针方法崩溃程序
- get_body来自 IHTMLDocument2 崩溃程序
- 是否有可能存在不会崩溃程序的内存问题
- 调试运行时出现奇怪的崩溃程序(Eclipse C++)
- 儿童对话框 - setWindowTexta或sendmessagea崩溃程序-MFC
- 顶点阵列GLFW崩溃C 程序
- 将值分配给Float数据类型崩溃程序
- OpenCV-将变量添加到类成员崩溃程序
- boost::interprocess::managed_shared_memory 崩溃程序
- 将枚举值分配给整数崩溃程序
- SDL 1.2 -> SDL 2.0(崩溃程序)
- 空析构函数崩溃程序:C++
- 冒泡排序崩溃程序c++
- Ofstream关闭崩溃程序
- 删除字符* 崩溃程序
- c++矢量擦除崩溃程序
- Lua_getglobal崩溃程序
- 通过Copy Constructor创建的e2打印崩溃程序
- RNG崩溃c++程序