Splitting first and last names from string

The following code shows bad memory access error (segmentation fault) when I run it. It does this right after it asks for name and the user has entered it. Help please:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <sstream>
using namespace std;

struct Name
{
  string first;
  string last;
};

struct Person
{
  //int MASTERY_LEVEL;
  int AGE;
  Name* MY_NAME;
};


int main()
{
  Person* Student = new Person;
  
  string name;
  
  cout <<"Enter your name please: ";
  stringstream Nstream (stringstream::in | stringstream::out);
  
  getline(cin, name);
  Nstream << name;
  
  Nstream >> Student->MY_NAME->first;
  cout <<"First ";
  Nstream >> Student->MY_NAME->last;
  cout <<"Last "<<endl;
  
  cout <<"Enter age: ";
  cin >> Student->AGE;
  
  cout << "My name is "<< Student->MY_NAME->first << " " << Student->MY_NAME->last <<endl;
  cout << "I am " << Student->AGE << " years old." <<endl;
  
}
Last edited on
Person* Student = new Person;

Here you allocate a Person named Student. But nowhere do you allocate memory and set Student->MY_NAME to point to it. Consequently it is pointing to some random place in memory and, of course, your code does weird things when you access it.

1
2
3
4
5
struct Person
{
    int AGE ;
    Name MY_NAME ;
};


is probably more appropriate. Of course, there isn't much reason to be using dynamic memory in main, either.. and you don't use a corresponding delete for your new.
Last edited on
You're not allocating Name* at Line 15. Therefore your write to it at line 31 is invalid and writing to invalid memory causing the crash.

On a side note, style wise. Please pick a naming convention and stick to it. You have different naming conventions everywhere =\
You would be better off with some constructors and destructors in your structs, so you can assign the required values to your member variables. Becuase the Name is declares on the heap inside the Person you need to ensure you release the memory allocated, hence the destructor. It is convention in c++ to use UPPERCASE variables for constants only.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <string>
using namespace std;

struct Name
{
	Name(string _first, string _last)
		: first(_first)
		, last(_last)
	{
	}

	string first;
	string last;
};

struct Person
{
	Person(int _age, string _first_name, string _last_name)
	{
		age = _age;
		name = new Name(_first_name, _last_name);
	}

	~Person()
	{
		delete name;
	}

	//int MASTERY_LEVEL;
	int age;
	Name* name;
};

int main()
{	
	Person person(33, "John", "Does");

	return 0;
}
Thanks for the replies. Yes it works now
Topic archived. No new replies allowed.