Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation Fault when getting user input

I have this:

    // Get database access parameters 
    const char* db = "codes", *server = "localhost", *user = "root", *pass = "pass";

    // Connect to the sample database.
    mysqlpp::Connection conn(false);
    if (conn.connect(db, server, user, pass)) {

        for (int i=0; i<10; ++i)
        {
            int d, count;
            cout << "Введите D\n";
            cin >> d;
            cout << "Введите количество записей при D=" << d << endl;
            cin >> count;
            for (int a=0; a<count; ++a)
            {
                char * name;
                int r,n1,n2;
                cout << "Введите R\n";
                cin >> r;
                cout <<"Введите n1 и n2\n";
                cin >> n1 >> n2;
                cout <<"Введите название\n";
                cin >> name;
                mysqlpp::Query query = conn.query();
                for (int j=n2-n1+1; j<n2; ++j)
                {
                    int k =pow(2,(j+r));
                    query << "insert into code (n,k,d, name) values (" << j << "," << k << "," <<d<<"," << mysqlpp::quote_only << name << ");";
                    query.execute(); 
                }
            }
        }
        conn.disconnect ();
        return 0;
    }
    else {
        cerr << "DB connection failed: " << conn.error() << endl;
        return 1;
    }
}

Sorry for posting all the code. I can compile the program with no errors, but in command line, it says "Segmentation fault". Whats this error? And how to solve it?

like image 738
Айк Саркисян Avatar asked Aug 21 '26 14:08

Айк Саркисян


1 Answers

You should allocate space for

char * name;

before writing to it.

If you know that name isn't going to be longer then MAXNAME then just define name to be

char name[MAXNAME+1]

That should solve your problem.

like image 71
Roman Byshko Avatar answered Aug 23 '26 05:08

Roman Byshko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!