0

Hi there,

I am implementing simple student class when i run the program it crashes after getting input for char* name. Program is as follows.

#include <iostream>

using namespace std;

class Student
{
    private:

        char* name;
        int rollNo;
        float cgpa;

    public:

        Student()
        {
            name = "";
            rollNo = 0;
            cgpa = 0.0;
        }

        void setName()
        {
            cout<<"Enter name : "<<flush;   //after input my program crashes
            cin >> name;
        }

        void setName(char* newName)
        {
            name = newName;
        }

        char* getName()
        {
            return name;
        }

        void setRollNo()
        {
            cout<<"Enter roll no : "<<flush;
            cin >> rollNo;
        }

        void setRollNo(int newRollNo)
        {
            rollNo = newRollNo;
        }

        int getRollNo()
        {
            return rollNo;
        }

        void setCgpa()
        {
            cout<<"Enter cgpa : "<<flush;
            cin >> cgpa;
        }

        void setCgpa(float newCgpa)
        {
            cgpa = newCgpa;
        }

        float getCgpa()
        {
            return cgpa;
        }
};

int main()
{

    Student s1;

    //s1.setName("Ahmad");
    s1.setName();
    cout<<"Name :\t\t"<<s1.getName() <<endl;
    //s1.setRollNo(23);
    s1.setRollNo();
    cout<<"Roll no :\t" <<s1.getRollNo() <<endl;
    //s1.setCgpa(3.45);
    s1.setCgpa();
    cout<<"Cgpa :\t\t" <<s1.getCgpa() <<endl;

    return 0;
}

Please see the comment where my program crashes, I don't know why ? Please help and explain, I am using Code Blocks. Thanks.

5
Contributors
4
Replies
25
Views
4 Years
Discussion Span
Last Post by rubberman
0

Your problem lies in line 17:

name = "";

Your name attribute is initialized to a read only memory having name to point to that memory location, but any writing is illigal, thus your error. If you would initialize name as this:

name = new char[200];

you would allocate memory on the heap, making writing legal for that variable, e.g. the cin part.

Also, why are you using C-style strings (null terminated sequences of characters) for names? Wouldn't std::string(Click Here) suite you better?

Edited by Lucaci Andrew

0

To add a little to Lucaci's words, any string in your code you make like this: "some letters" is a string literal. It is for reading only. Trying to write to that memory is forbidden. Look up string literal for all the details.

0

What all these good people said. In any case, your compiler should have emitted a warning that your were initializing a non-const string to a const char* "". DO NOT disable compiler warnings, unless you really know what you are doing!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.