user69514 user69514 - 2 months ago 11
C++ Question

Segmentation fault when using stream extraction into a char pointer

I have a question. I have the following

struct
:

typedef struct{
int vin;
char* make;
char* model;
int year;
double fee;
}car;


Then I have the following method that asks the user for the make of a car and returns it as a char pointer:

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


Then I have a temp car
struct
:

car tempCar;


And I am trying to assign a value to it this way:

tempCar.make = askMake();


It compiles fine, but I get a segmentation fault at runtime.

Answer

You have to allocate memory for tempMake.

Try this:

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

Don't forget to free with delete[] the memory that you allocated.

If you don't want memory leaks, you can avoid this using smart pointers like boost::shared_ptr or boost::scoped_ptr or similar. You can see more about this here.