Uninitialised value was created by a stack allocat

2019-04-26 18:29发布

问题:

I debugged my code using the tool Valgrind. It shows this error at this function. I have given below the error and My function. I don't know what is the problem here ? How can I rectify it ? My Error Is.

Uninitialised value was created by a stack allocation at 0x80996D7: cdtojd(std::string const&)

My Code is.

double cdtojd(const string &cdate);

double cdtojd(const string &cdate)
{
    int dd,mm,yy;
    int y,m;
    double jd=0;

    //mm = atoi(cdate.substr(0,2).c_str());
    //dd = atoi(cdate.substr(2,2).c_str());
    //yy = atoi(cdate.substr(4,4).c_str());

    sscanf(cdate.c_str(),"%2d%2d%4d",&mm,&dd,&yy);

    //cout<<mm<<"..."<<dd<<"...."<<yy<<endl;

    y = (yy - 1900) * 372;

    m = (mm-1) * 31;

    jd = dd + m + y;

    return jd;
}

回答1:

The meaning of the error is essentially that you're using a variable before you assign to it. The only variables this can possibly apply to are dd, mm, yy.

This means that your sscanf call is not writing to all three of them. This will occur if you pass in a date that isn't completely specified.

Note that sscanf returns a value to tell you how many of the variables it wrote to. You should be checking the return value, and aborting (or filling in some default values) if it doesn't return 3, because then not all your fields will have been filled.



回答2:

There's no error checking for sscanf and that means some variables might remain uninitialized and afterwards used, e.g.

std::string str = "invalid";
unsigned int dd,mm,yy;
cout << dd << " " << mm << " " << yy << endl;
cout << "Arguments read: " << sscanf(str.c_str(),"%2d %2d %4d",&mm,&dd,&yy) << endl;
cout << dd << " " << mm << " " << yy;

the above code might emit as output:

32550 3249645428 32550
Arguments read: 0
32550 3249645428 32550

where all three arguments remain uninitialized.



标签: c++ valgrind