为什么这个程序会崩溃?

时间:2018-01-31 16:24:35

标签: c++

#include<iostream>
#include <cstring>
using namespace std;  
typedef struct {char *str;}String;
int main(){
    String name,add;
    cout<<"Name: ";
    cin>>name.str;
    cout<<"\n\tadd: ";
    cin>>add.str;
    cout<<"\n\tName:"<<name.str;
    cout<<"\n\t Add:"<<add.str;
    return 0;
}

输入成功,然后程序崩溃 显示错误:停止工作

2 个答案:

答案 0 :(得分:4)

不,不,不,只需使用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<<"\n\tadd: ";
    cin>>add;
    cout<<"\n\tName:"<<name;
    cout<<"\n\t Add:"<<add;
    return 0;
}

至于您的问题与原始代码有关,那就是您没有为char*分配任何内存,并且正在读取不属于您的内存。

答案 1 :(得分:2)

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;
相关问题