使用流提取到char指针时出现分段错误

use*_*514 5 c++ pointers

我有个问题.我有以下内容struct:

typedef struct{
    int vin;
    char* make;
    char* model;
    int year;
    double fee;
}car;
Run Code Online (Sandbox Code Playgroud)

然后我有以下方法询问用户制作汽车并将其作为char指针返回:

char* askMake(){
    char* tempMake = NULL;
    cout << "Enter Make:" << endl;
    cin >> tempMake;
    return tempMake;
}
Run Code Online (Sandbox Code Playgroud)

然后我有一辆临时车struct:

car tempCar;
Run Code Online (Sandbox Code Playgroud)

我试图以这种方式为它分配一个值:

tempCar.make = askMake();
Run Code Online (Sandbox Code Playgroud)

它编译得很好,但是我在运行时遇到了分段错误.

Jer*_*fin 12

你没有分配任何内存tempMake指向.当您读入数据时,它会将其读入任何tempMake指向的随机位置.

摆脱指针,std::string而是使用,以使生活更简单.


coe*_*udo 8

你必须为内存分配tempMake.

试试这个:

char* askMake(){
    char* tempMake = new char[1024]; //Arbitrary size
    cout << "Enter Make:" << endl;
    cin >> tempMake;
    return tempMake;
}
Run Code Online (Sandbox Code Playgroud)

不要忘记释放delete[]你分配的内存.

如果您不希望内存泄漏,可以使用boost :: shared_ptr或boost :: scoped_ptr等智能指针来避免这种情况.你可以在这里看到更多相关信息.


Jef*_*ite 6

你真的想在这里使用std :: string而不是char*.问题是您正在尝试将用户输入读入尚未分配的内存(tempMake).

std::string askMake(){
    std::string tempMake;
    cout << "Enter Make:" << endl;
    cin >> tempMake;
    return tempMake;
}
Run Code Online (Sandbox Code Playgroud)

你也可能想在你的'car'结构中使用std :: string而不是char*.