views:

197

answers:

3

I'm having problem with vector, (in the usage of push_back) but it only appears when using additional g++ flag -O2 (I need it).

#include <cstdio>
#include <vector>

typedef std::vector<int> node;
typedef std::vector<node> graph;

int main()
{
    int n, k, a, b, sum;
    bool c;
    graph g(n, node());
    c = scanf("%i%i", &n, &k);

    for(int i=0; i<n; i++)
    {
        sum=2;
        for(int j=0; j<i; j++)
            sum*=2;
        for(int j=0; j<sum; j++)
        {
            if(j%2==0)
                c = scanf("%i", &a);
            else
            {

                c = scanf("%i", &b);
                a += b;
                g[i].push_back(a); //---------------LINE WHICH CAUSES SEGMENTATION FAULT
            }

        }
    }

    for(int i=n-2; i>=0; i--)
    {
        for(size_t j=0; j<g[i].size(); j++)
        {
            if(g[i+1][(j*2)] >= g[i+1][(j*2)+1])
                g[i][j] = g[i+1][j*2];
            else
                g[i][j] = g[i+1][(j*2)+1];
        }
    }

    printf("%i\n", g[0][0]);

    return 0;
}
+3  A: 

Initializing the vector with n before the input operation means you're invoking the dreaded Undefined Behavior. As stated here, the program is allowed to do anything after that.

sbi
Isnt n initialized in line: c = scanf("%i%i", ?If not, how should I do it in this case?Thanks for help :)
user85423
@user85423: Yes, it is (assuming scanf succeeds), but you use n *before* you do that. So I suppose sbi should have said "You don't initialize `n` before you use it" instead of "You never".
sepp2k
@sepp2k: I fixed that while you added your comment. I just didn't read the code further than the use of the uninitialized variable...
sbi
+4  A: 

I think you have:

graph g(n, node());
c = scanf("%i%i", &n, &k);

in the reverse order. As it stands, the variable 'n' which you use to size graph is not initialised.

anon
right, i didnt notice :)thanks
user85423
+2  A: 

Works perfectly if you initialize n as I already mentioned in my comment. Change the first lines to:

int n, k, a, b, sum;
int c;
c = scanf("%i%i", &n, &k); // initialize n *first*
if(c != 2) return -1; // scanf does not return bool but the number of parsed arguments
graph g(n, node());
AndiDog