I don't what's wrong with this simple piece of code I wrote. It keeps crashing.

Output Screenshots:
http://i.imgur.com/8xwet8m.png
http://i.imgur.com/FXBa8YM.png

#include <iostream>
#include <stdlib.h>
#include <conio.h>

using namespace std;

int main()
{
    char *strg;
    cin>>strg;
    cout << "Hello world!"<< strg<<endl;
    getch();
    return 0;
}

Recommended Answers

All 4 Replies

C-style strings don't work like that. A variable of type char* is a pointer, and as such it actually has to point to a valid memory location before you can modify information in it. I advise against using char* with cin anyway because there isn't a guarantee that what you input will actually fit in the buffer.

You have two possible solutions to this problem:

1) Use std::string for your string instead.
2) Turn strg into an array instead of a pointer, and use cin.getline(strg, XXX) where XXX is the length of your array.

I turned it into an array and am using cin to accept it. (strg[10]; cin>>strg;) Would this be ok?

No. It's unsafe, because as I stated before, there is no guarantee that the buffer will fit what you type into it. As you have it right now, strg will hold nine characters plus the terminating character ('\0'). If the user types a string that is ten characters or more, your program may behave erratically or it may crash, either instantly or somewhere down the road.

Instead of using cin >> strg;, you should use cin.getline(strg, 10); in this case, which will read a line of text that the user types, and makes sure not to fill your array anywhere past those ten characters that you can hold.

Do this instead:

using namespace std;
string somestuff;    
cin >> somestuff;
cout << somestuff << endl;

As Tumlee said, what you did was not only unsafe, but guaranteed to segfault! A pointer has to point to valid memory. You had two major problems:

  1. The pointer was not initialized.
  2. Even if it was initialized to 0 (null) it would not be a valid address - writing to it would dump core.
  3. Even if it was initialized with a valid pointer to data, using such as new char[256] the input could still overflow the buffer. The C++ string class will deal with all of that for you. :-)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.