-6

I have a code for outputting to a file from a 2D vector Kvec. The name of the file is inputted in the string s, and I'm using sprintf to convert the int into the char to be inputted into the string. Then I used s.c_str() to input it as the name of the file I want to open. So when I try running the code I get a segfault when I try to open the file using foo.open(). It's got such little scope for error that I'm baffled where could the mistake be.

I've already used this technique for working on the strings to open files so I know sprintf and s.push_back() work. Where am I going wrong?

    fstream foo;

    string s;
    char g[10],j[10];
    int b=0;

    sprintf(j,"L_%dLprime_%dM_%dMprime_%d",L,Lprime,M,Mprime);
    for(int i=0;i<(int)strlen(j);i++)
        s.push_back(j[i]);

    for( int D = 0; D < 1000; D++ )
    {
        s+="MSF-Dval";

        sprintf(g,"%d",D);
        for(int i=0; i<(int)strlen(g); i++)
            s.push_back(g[i]);
        s+=".dat";

        foo.open(s.c_str(), ios::in | ios::out | ios::binary );

        cout<<"Is this working?"<<endl;

        b = 0;

        for(L1=abs(L-D);L1<L1max;L1++)
        {
            if( (D>abs(L+L1) || D<abs(L-L1)) && b == 0)
            {
                if(remove(s.c_str())!=0)
                    cout<<"error deleting file";
                break;
            }
            b = 1;

            if(foo.is_open())
            {
                foo << L1 << "  "<<Kvec.at(L1).at(L1+D-abs(L-L1)).re<<" "<<Kvec.at(L1).at(L1+D-abs(L-L1)).im<<endl;
            }
            else
                cout<<"not open";

        }
        foo.close();

        s.erase(8,4 + (int)strlen(g));

    }
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
pyroscepter
  • 205
  • 1
  • 3
  • 9

1 Answers1

2

Your problem is in these two lines.

char g[10],j[10];
sprintf(j,"L_%dLprime_%dM_%dMprime_%d",L,Lprime,M,Mprime);

You allocate a 10 character buffer for j, and then proceed to write more than 20 characters into that buffer, overrunning it, and invoking Undefined Behavior.

Once you're into UB, a segfault is just one of many things that will go wrong.

Ryan Bemrose
  • 9,018
  • 1
  • 41
  • 54
  • Ah thanks so much! I wonder why the fault is when I try to open a file rather than the sprintf statement. That would've been much easier to debug. – pyroscepter Jun 29 '16 at 07:48
  • UB need not cause an instant crash or even a crash at all. I would replace this `c` code with `c++`. – drescherjm Jun 29 '16 at 09:26