Re: Why is my program crashing?

Posted 29 September 2012 - 02:01 PM

Given that this is C++, consider std::string instead of char*.

It's not just the added work of using C strings. Its also about the robustness of your own code. For example, you need to comply with the rule of three, which you probably will violate if your code looks like this already.

And one more point. You do understand that when you dynamically allocate, you are responsible for deallocating too, right?

Re: Why is my program crashing?

It's customary to allocate space for the strings where you are going to input data into. You don't seem to be doing that for the name or email.

Ah, simple mistake. Thank you!

Oler1s, on 29 September 2012 - 02:01 PM, said:

Given that this is C++, consider std::string instead of char*.

It's not just the added work of using C strings. Its also about the robustness of your own code. For example, you need to comply with the rule of three, which you probably will violate if your code looks like this already.

And one more point. You do understand that when you dynamically allocate, you are responsible for deallocating too, right?

Yeah, that's what I did. I'm using the data type string instead of char* now.
And yes, I do understand, I just tend to forget sometimes lol
Thanks for the replies

Re: Why is my program crashing?

Posted 29 September 2012 - 02:19 PM

struct friends
{
char *name;
char *email;
};

name and email are only pointers, they can only point to somewhere in memory. When you create the pointer it points to some garbage value in memory, most likely an address that your program does not own. when you try writing to this memory location, you will most likely (if your lucky) get a segmentation fault. If you are going to use pointers for your strings, then you need to allocate memory for "your program" on the run time heap using "new", or alternatively (and a better way) would to pre-allocate enough memory as char array for the names.

example

struct friends
{
char name[50];
char email[50];
};

However, since you are using C++ use can use a std::string. This will take care of all the memory allocation, and reallocation if your string needs to resize in length.