Home > database >  SIGSEGV error in C with character pointer
SIGSEGV error in C with character pointer

Time:10-04

Why I am getting a SIGSEGV error in this program:

#include<iostream>
#include<cstring>
using namespace std;

int main(void)
{
    char *name1, *name2;
    cout<<"Enter your name: ";
    cin>>name1;
    strcpy(name2, name1);
    cout<<"Your name is: "<<name2<<endl<<endl;

    return 0;
}

Please explain to me why I am getting a SIGSEGC error. This program shows error with character pointer (char *name1, *name2) but, works fine with character arrays (char name1[20], name2[20]) and also with dynamic memory allocator new (char *name1=new char[20] and char *name2=new char[20])

CodePudding user response:

Your program segfaults because you have not allocated memory for name1 and name2. Your program is writing the input from cin into a undefined memory location which causes it to crash with SIGSEGV.

CodePudding user response:

These declared variables

char *name1, *name2;

are not initialized and have indeterminate values.

As a result these statements

cin>>name1;
strcpy(name2, name1);

invoke undefined behavior.

Use objects of the standard class std::string. For example

#include <string>

//...

std::string name1, name2;
//...
cin>>name1;
name2 = name1;
//...

Otherwise you need to declare character arrays for example like

const size_t N = 100;
char name1[N], name2[N];

and then to write

cin.getline( name1, sizeof( name1 ) );
strcpy(name2, name1);
  • Related