Urgent! Please help...strcpy gives seg fault

I am trying to practice different concepts in C++ programming. Following is the program which compile successfully but gives seg fault at runtime.

#include <iostream>
#include <string.h>
using namespace std;

class A
{
char *name;
int i,j;
const double k;
static float l;
int &m;

public:

A():k(9),i(9),m(i)
{
name = new char[10];
}
A(int c);
/*A(const A& a)
{
i=a.i;
j=a.j;
l=a.l;
} */
A& operator=(const A& a)
{
i=a.i;
j=a.j;
l=a.l;
return *this;
}
void setval(const char *);
void getval();

};

float A::l=6;

A::A(int c):k(7),i(c/2),m(c)
{
j=3;
name = new char[10];
}
void A::setval(const char* s)
{ i=11;j=22;l=33;m=44;
strcpy(name,s);
}
void A::getval()
{ cout<<"i="<<i<<" "<<"j="<<j<<" "<<"k="<<k<<" "<<"l="<<l<<" "<<"m="<<m<<" "<<"name="<<name<<endl;
}

int main ()
{

A a0;
cout<<"values in a0 before\n";
a0.getval();
A a1(5);
A a2;
A a3=a2;
cout<<"values in a3 after a3=a2 \n";
a3.getval();
cout<<"values in a2 before \n";
a2.getval();
a2.setval("Tom"); // <<<<============Here it does not seg fault.
cout<<"values in a2 after a2 setval \n";
a2.getval();
cout<<"values in a3 after a2 setval \n";
a3.getval();
cout<<"values in a1 before\n";
a1.getval();
a1.setval("Tindol"); // <<<<============But here it seg faults.
cout<<"values in a1 after\n";
a1.getval();
a0=a2=a1;
cout<<"values in a0 after\n";
a0.getval();

return 0;
}
A::A(int c):k(7),i(c/2),m(c) m is a reference.
You binds it to temporary variable c.
After end of the constructor it any attempt to write it will overwrite some random memory.
By some chance address of c-stirng you pass in setval is in the exact same area. When you are trying to assign 44 to m, it overwrites pointer value. You can see it for yourself by commention out m=44 in setval.

Solution: never bind references to variables which lifetime is shorter than reference.
Second problem: you are trying to output string contained in name member. But it value is not initialised yet. So attempts to read it lead to undefined behavior. Internally there is probably no null terminator and output operator tries to read until it hit unallocated memory.
Thank you so much for your reply :)
I could understand your comment, and correct my program.
In your second comment did you mean to null terminate string after using strcpy ?
or you advice me to use some other string copy function like strncpy ?
In your second comment did you mean to null terminate string after using strcpy ?
No, I meant that your name pointer here point to uninitialised memory.
1
2
3
4
5
A() : i(9), k(9), m(i)
{
    name = new char[10];
    //what will std::cout << name output here?
}
Topic archived. No new replies allowed.