Getting Segmentation Fault

Guys,

I am getting Segmentation fault (core dumped) for the following code when I enter name .
Please Help .
Note: I am Using gcc Compiler

#include<iostream>
using namespace std;

int main()
{
char *name;

cout<<"\nEnter Name::";
cin>>name;

cout<<"\nName is ::"<<name<<endl;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
using namespace std;

int main()
{
    char name[20];

    cout << "\nEnter Name::";
    cin >> name;

    cout<<"\nName is ::"<< name << endl;
}
// but please do this:
string name;
cout << ..
cin >> name;
cout << ... << name << endl;
Last edited on
The reason for the crash is that you haven't allocated any memory for the name. All you've done is declared a pointer - but you haven't initialised it to point to any area of memory that's been reserved for the string. So you're attempting to store the name in a random area of memory.

bugbyte's post shows how to create an array to hold the name, on the stack. I'd also second his recommendation to learn how to use std::string, rather than C-style character arrays.
Last edited on
Thanks Guys
Topic archived. No new replies allowed.