Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault when using stream extraction into a char pointer

Tags:

c++

pointers

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.

like image 896
user69514 Avatar asked Feb 24 '10 20:02

user69514


1 Answers

You haven't allocated any memory for tempMake to point at. When you read in the data, it's reading it into whatever random location tempMake happens to point at.

Get rid of the pointers and use std::string instead to make life a lot simpler.

like image 69
Jerry Coffin Avatar answered Sep 20 '22 15:09

Jerry Coffin