简体   繁体   中英

Overwriting Vectors C++

I was trying to overwrite values into my vector:

  for (i = 0; i < 50; i++)
  {      
        LJ.clear();
        LJ.reserve(210);

        //Calculate Lennard-Jones potential of every pair
        for(itr = 0; itr < 210; itr++)
        {
            term1 = pow(r[itr], 12);
            term1 = 1/term1;
            term2 = pow(r[itr], 6);
            term2 = 2/term2;
            LJ.push_back(term1 - term2);
        }

        //Calculate the initial Energy in the system Ei
        Ei = accumulate(LJ.begin(), LJ.end(), 0.0);
        Ei = Ei/2;
        cout << Ei << endl;
    }

However, whenever I came across the loop twice, the capacity of the vector got some garbage value and when i tried to push an item in, I got a segmentation fault...and if i left our the reserve part, I still got an a seg fault

However, whenever I came across the loop twice, the capacity of the vector got some garbage value [...]

This is a clear indication of memory corruption.

You probably have an array on the stack and you are overwriting the stack past the array limit, "stepping" on the vector's toes. Whichever array is closer to the LJ declaration is the likely target of an unfortunate write.

If r is a std::vector too, try changing the inner loop to the following:

// assuming r is a vector<double>
for(vector<double>::iterator it = r.begin(), ite = r.end(); it != ite; ++it){
  // use *it instead of r[itr];
  term1 = pow(*it, 12);
  term1 = 1/term1;
  term2 = pow(*it, 6);
  term2 = 2/term2;
  LJ.push_back(term1 - term2);
}

However, if r is a statically allocated array (ie, on the stack), change it to this:

for(int itr = 0; itr < sizeof(r)/sizeof(r[0]); ++itr){
  // same content...
}

If that doesn't segfault, r is does not have 210 elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM