Handling pointer in vector C++ - c++

Having problem using the vector in C++.
The following code is having this Runtime Error :
* Error in `./a.out': double free or corruption (out): 0x0000000001e5d050 *
=== Backtrace: ===
.
.
.
I have written this code.
int main(){
vector<int> ve;
int n;
cin>>n;
for(int i=1; i<n+1; i++)ve.push_back(i);
int last, sec_last, ans;
while(!(ve.empty())){
ans = ve.back();
last = ve.back();
ve.pop_back();
sec_last = ve.back();
ve.pop_back();
ve.push_back(last + sec_last + last*sec_last);
}
cout<<"\nline 20\n";
cout<<ans<<"\n";
cout<<"\nline 22\n";
}
Please explain me what does this error mean, and how can I correct it...

"Calling back / pop_back on an empty container is undefined" -- Internet
While loop condition prevents you only once, until the vector ve is modified again by pop_back. In that case there is possibility that vector is empty and calling back on empty vector will likely result into a crash.
while(!(ve.empty())){
ans = ve.back();
last = ve.back();
ve.pop_back(); // <---- Vector could become empty
sec_last = ve.back(); // <---- If vector is indeed empty, then undefined behavior
ve.pop_back();
ve.push_back(last + sec_last + last*sec_last);
}

Related

make_heap memory access problem error: Abort (core dumped)

I am recently writing a SRPT program. I need to use vector and convert the vector into heap using make_heap.
However, I got error on one specific test case int LB = estimateLB({{2, 2}, {2, 6}}, 2);
I tested the code on two machines:
Ubuntu will cause the bug, macOS will compile correctly.which is really weird.
The error:
The brief estimateLB function:
int estimateLB(vector<pair<int, int>> proc, int n) {
int diff = 0;
int i = 1;
// 1. cause error
vector<int> heap;
heap.push_back(proc[0].first);
make_heap(heap.begin(), heap.end(), greater<>{});
// 2. works
// vector<int> *heap = new vector<int>();
// heap->push_back(proc[0].first);
// make_heap(heap->begin(), heap->end(), greater<>{});
// memory access problem
diff = proc[i].second - proc[i - 1].second;
while (diff > 0) {
int temp = heap.front();
if (diff >= temp) {
pop_heap(heap.begin(), heap.end(), greater<>{});
heap.pop_back();
diff -= temp;
}
}
heap.push_back(proc[i].first);
push_heap(heap.begin(), heap.end(), greater<>{});
return 0;
}
If I initialize the vector using pointer, the bug seems to be fixed. For now, I only know the two ways will allocate memory at different location(stack or free storage). Will this mechanism cause this error? Any idea?
Thanks in advance.
Thanks for the help from #Konrad Rudolph. I end up changing my while loop condition to check the heap is empty or not first.
while (diff > 0 && heap->begin() != heap->end()) {}
Thanks for all the help :)

incorrect checksum for freed object - object was probably modified after being freed

I was hoping the return values in c++11 are already moved or optimized out as explained in here: c++11 Return value optimization or move?
However I am having this exception below. "inference(4160,0x7fffb832e380) malloc: error for object 0x7fc415f00a10: incorrect checksum for freed object - object was probably modified after being freed.
set a breakpoint in malloc_error_break to debug".
The code:
vector<double> sp_peaks = dsp.diff(zero_sp_cropped);
sp_peaks = dsp.sign(sp_peaks);
sp_peaks = dsp.diff(sp_peaks);
The third line is giving the error.
The sign and diff methods are below.
vector<double> SignalProcessing::diff(vector<double> &signal) {
/*
* Performs the diff filter on the input signal and returns the value.
* The returned signal has length 1 less than the input signal.
* */
vector<double> res(signal.size()-1); // -1 because the first one cannot have a diff
for (int i = 1; i < signal.size(); ++i) {
res[i] = signal[i]-signal[i-1];
}
return res;
}
vector<double> SignalProcessing::sign(vector<double> &signal) {
/*
* Maps the input signal into a signal of {-1.0,1.0} values by their sign values.
* Positive values will be mapped to 1.0 while negative will be mapped to -1.0
* */
vector<double> res(signal.size());
for (int i = 0; i < signal.size(); ++i) {
if (signal[i] > 0)
res[i] = 1.0;
else
res[i] = -1.0;
}
return res;
}
The error disappears if I place a breakpoint and debug. Could you explain why this is happening and what is a good practice of returning an std container?
Thank you in advance!
Anil

Deleting 2d array in C++

Can some one tell me what is wrong in the for loop? When I run it, it interrupts. I tried to debug to see what is wrong, I noticed that in the for loop it just stops:
#define MAX_POPULATION 64
float **tr_pop;//Tournament candidates
float **matingPool;//Mating pool
tr_pop=new float *[m];
matingPool=new float *[m];
for(l=0;l<m+1;l++)//allocating
{
tr_pop[l]=new float[MAX_POPULATION];
matingPool[l]=new float[MAX_POPULATION];
}
for ( int r = 0; r < row; ++r )//deleting
{
delete [] matingPool[r];//Stops here (not ending program just frozen)
delete [] tr_pop[r];
}
delete [] tr_pop;
delete [] matingPool;
=======OK. PROBLEM SOLVED=======
Here is the reason:
I just changed the MAX_POPULATION into the MAX_POPULATION+1 and it worked.
for(l=0;l<m+1;l++)
{
tr_pop[l]=new float[MAX_POPULATION+1];
matingPool[l]=new float[MAX_POPULATION+1];
}
Because in another function I think I was doing violation:
void crossover()
{
int p1,p2,i,j;float tempBit;
p1=m/3;
p2=(2*m)/3;
for(j=0;j<MAX_POPULATION;j++)
{
for(i=p1;i<p2;i++)
{
tempBit=matingPool[i][j];
matingPool[i][j]=matingPool[i][j+1];//THE VIOLATION POINT (I THINK)
matingPool[i][j+1]=tempBit;
}
j++;
}
As you can see, when j = MAX_POPULATION at the end of the loop, i was trying to reach MAX_POPULATION + 1. So I changed the allocations for columns, and the problem solved :)
You're running into undefined behavior:
for(l=0;l<m+1;l++)//allocating
{
tr_pop[l]=new float[MAX_POPULATION];
}
should be
for(l=0;l<m;l++)//allocating
{
tr_pop[l]=new float[MAX_POPULATION];
}
You're allocating m elements for each of the arrays and try to access m+1.
You are allocating m float* but in for loop you are iterating from 0..m while allocating memory, it should from 0..m-1. For that you need to chnage the for loop to : for(l=0;l<m;l++).

C++ code crashes with "free(): invalid next size"

I have written a small program which uses function pointers to do some numerical calculations.
double polynom(const int j, const double xi) {
return pow(xi, j);
}
/**
* Calculate the legendre_polynom l_end on a certain position xi.
*/
double legendre_polynom(const int l_end, const double xi) {
vector <double> p_l(l_end+1);
p_l[0] = 1.0;
p_l[1] = xi;
for (int x = 2; x <= l_end; x++) {
// p_l = ((2x-1) * p_{x-1} - (x-1) * p_{x-2}) / l
p_l[x] = ((2 * x - 1) * p_l[x - 1] - (x - 1) * p_l[x - 2]) / x;
}
double result = p_l[l_end];
return result;
}
The program crashes with an unusual free() error. If I change the function pointer to the first function (polynom) it works fine, but it fails with legendre_polynom.
I already debugged that far that it breaks right after exiting that function and before the other code continues.
*** glibc detected *** blub: free(): invalid next size (fast): 0x0804f248 ***
======= Backtrace: ========= /lib/i386-linux-gnu/libc.so.6(+0x6ebc2)[0xb7d70bc2]
/lib/i386-linux-gnu/libc.so.6(+0x6f862)[0xb7d71862]
/lib/i386-linux-gnu/libc.so.6(cfree+0x6d)[0xb7d7494d]
...
number2(_ZN9__gnu_cxx13new_allocatorIdE10deallocateEPdj+0x11)[0x804bc8b]
number2(_ZNSt12_Vector_baseIdSaIdEE13_M_deallocateEPdj+0x25)[0x804bbc3]
number2(_ZNSt12_Vector_baseIdSaIdEED1Ev+0x37)[0x804ba33]
number2(_ZNSt6vectorIdSaIdEED1Ev+0x38)[0x804b8a0]
number2(_Z16legendre_polynomid+0x13f)[0x804af9b]
So my question is what is wrong here?
There is no error in that code, provided that you always call that function with l_end >= 1.
When l_end == 0 instead there is an out of boundary write operation in p_l[1] = xi;.
Note however that you cannot infer that this is the function having the problem just because this is where you get a crash or just because not calling this function you have no crash.
An error is an error and a crash is a crash. They are completely distinct in C++; the sooner you realize this important fact the better. There may be an error somewhere else and this function may be just the victim.
If you see a crash then there is an error. If you see no crash you know nothing (the error may be still present).

Stack push causes critical error

I am new to C++ and working with STL container at the moment.
I got a serious problem executing a nodeStack.push(startnode) - the compiler shows up a
Critical error detected c0000374
Followign code shows the function where the mentioned error occurs:
vector<int> Graph::iterativeDepthSearch(map<int, vector<int>> adjlist, int startnode) {
stack<int> nodeStack;
vector<int> visitList;
// Knotenbesuchsliste initialisieren
int* val = new int(adjlist.size());
for (int i = 0; i < (int) adjlist.size(); i++) {
val[i] = 0;
}
int cnt = 1;
nodeStack.push(startnode);
....
}
The error occurs in the line nodeStack.push(startnode);, startnode is initialized with 0.
try int* val = new int[adjlist.size()]; you are currently allocating a single int and initializing its value, not allocating an array of ints.
The stack structure is corrupting because it is next to your pointer in the memory stack.
nodeStack.push isn't really your problem. You are declaring int* val - a pointer to int, then initializing the integer at val with the size of the list. You really want
int *val = new int[adjlist.size()];
It's possible that you are using an x86 DLL; when I got this error in VS4.5, I changed my target platform to x86 and switched to .Net 4.0. That worked for me.