为什么这个程序崩溃

Why does this program crashes?

本文关键字:崩溃 程序 为什么      更新时间:2023-10-16
#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;