Segmentation error when using thread extraction in 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, which asks the user for the car brand and returns it as a char pointer:

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

Then I have temp car struct:

car tempCar;

And I'm trying to assign it a value as follows:

tempCar.make = askMake();

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

+5
source share
6 answers

You must allocate memory for tempMake.

Try the following:

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

Remember to free the delete[]allocated memory.

, , , boost:: shared_ptr boost:: scoped_ptr . .

+8

tempMake . , tempMake.

std::string, .

+12

std::string char *. , (tempMake), .

std::string askMake(){
    std::string tempMake;
    cout << "Enter Make:" << endl;
    cin >> tempMake;
    return tempMake;
}

, , std::string char * "car".

+6

segfault, . cin, , . std::string :

std::string askMake() {
    std::string temp;
    cout << "Enter Make:" << endl;
    cin >> temp;
    return temp;
}
+1

, , : tempMake new malloc, std:.

, struct . , , . . , , , , - . , , ? , , , ? , , ? .

, , . ++ , std::string. C a char ** ( x) :

int askMake(char** x)
{
    char tempMake[100];//or some value you know to be large enough
    cout << "Enter Make:" << endl;
    cin >> tempMake;//i would use cin.get() so you know the length of the string.
    //so let pretend we have that length in a variable called stringLen.

    *x = new char[stringLen];
    for(int i = 0; x && i < stringLen; i++)
    {
        (*x)[i] = tempMake[i];
    }

    if(x)
       return 0;
    else
       return 1;
}
0

, , char* std::string. std::string, :

#include <string>
struct car
{
  int vin;
  std::string make;
  std::string model;
  int year; 
  double fee; 
}; 

std::string askMake()
{
  std::string make;
  cout << "Enter Make:" << endl;
  cin >> make;
  return make;
}

int main()
{
  car tempCar;
  tempCar.make = askMake();
}
0

All Articles