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

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).

Related

C++ time limit exceeded when it doesn't even execute the function

While I was solving a problem in LeetCode, I found something very strange.
I have this line which I assume gives me a time limit exceeded error:
s.erase(i-k, k);
when I comment(//) this line, it doesn't show me time exceed error, but the strange part was, it has never executed even when i didn't comment it.
below is the entire code.
and Here is the problem link.
class Solution {
public:
string removeDuplicates(string s, int k) {
char prev = s[0];
int cnt = 1;
cnt = 1;
for(int i = 1; i < s.size() + 1; i++){
if(s[i] == prev){
cnt++;
} else {
if(cnt == k){
// when input is "abcd" it never comes to this scope
// which is impossible to run erase function.
s.erase(i-k, k);
i = 0;
}
if(i >= s.size()) break;
cnt = 1;
prev = s[i];
}
}
return s;
}
};
When Input is "abcd", it never even go to the if scope where 'erase' function is in.
Although 'erase' function never run, it still affect on the time complexity, and I can't get the reason.
Does anyone can explain this? or is this just problem of LeetCode?
Many online contest servers report Time Exceeding when program encounters critical error (coding bug) and/or crashes.
For example error of reading out of bounds of array. Or dereferencing bad (junk) pointers.
Why Time Exceeded. Because with critical error program can hang up and/or crash. Meaning it also doesn't deliver result in time.
So I think you have to debug your program to find all coding errors, not spending your time optimizing algorithm.
Regarding this line s.erase(i-k, k); - it may crash/hang-up when i < k, then you have negative value, which is not allowed by .erase() method. When you get for example i - k equal to -1 then size_t type (type of first argument of erase) will overflow (wrap around) to value 18446744073709551615 which is defnitely out of bounds, and out of memory border, hence your program may crash and/or hang. Also erase crashes when there is too many chars deleted, i.e. for erase s.erase(a, b) you have to watch that a + b <= s.size(), it is not controlled by erase function.
See documentation of erase method, and don't put negative values as arguments to this method. Check that your algorithm never has negative value i.e. never i < k when calling s.erase(i-k, k);, also never i-k + k > s.size(). To make sure there is no program crash you may do following:
int start = std::min(std::max(0, i-k), int(s.size()));
int num = std::min(k, std::max(0, int(s.size()) - start));
s.erase(start, num);

C++ Karatsuba long integer algorithm error

i got this error = Unhandled exception at 0x7A5B1088 (ucrtbased.dll) in algorthmprokect1.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x006B2FF4). occurred
i don't know where i have a mistake i am using strings because i need to get integers from file and they has 1000 digits
Update:After Debugging i realized that else statement runs infinite number of times but i still didn't found the solution.
string karatsuba(string X,string Y) {
if (X.length()==1 || (X.length()==2 && ((X.substr(0, 1).compare("-") == 0))))
{
int buf = stoi(X) * stoi(Y); //multiply if int has single digit
return to_string (buf);
}
else
{
string X1 = X.substr(0, (X.length()/2)); //divide half to X
string X2 = X.substr((X.length() / 2), X.length());
string Y1 = Y.substr(0, (Y.length() / 2)); // divide half to Y
string Y2 = Y.substr((Y.length() / 2) , Y.length() );
string U= karatsuba(X1, X2);
string V = karatsuba(Y1, Y2);
string W = karatsuba(to_string(stoi(X1) - stoi(X2)), to_string(stoi(Y1) - stoi(Y2)));
string Z = to_string(stoi(U) + stoi(V) - stoi(W));
string P = to_string(pow(10, X.length()) * stoi(U) + pow(10, X.length() / 2) * stoi(Z) + stoi(V));
return P;
}
}
This code is not working properly because of the infinite recursion.
But this is not the main problem of it.
The main problem is: it's a brilliant example of how not to do. You are severe underqualified to do such tasks. There is no point in attempts to fix this code, you must simply put it into trash. I would recommend to start with the GNU MP library. You can learn much from the source code and documentation there how to work with big integers and implement big integer algorithms. You may also try to read this source.

Handling pointer in vector 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);
}

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

Computing median of std::vector<double> causing segfault

The following function is supposed to compute the median of a std::vector<double>.
double vecMed(vector<double>& vec) {
vector<double> copyVec = vec;
sort(copyVec.begin(), copyVec.end());
if( copyVec.size()%2 == 0)
return (copyVec[floor(static_cast<double>(copyVec.size())/2.0)] + copyVec[ceil(static_cast<double>(copyVec.size())/2.0)]) / 2.0;
else
return copyVec[copyVec.size()/2];
}
I'm getting a segfault on this line, sometimes:
return (copyVec[floor(static_cast<double>(copyVec.size())/2.0)] + copyVec[ceil(static_cast<double>(copyVec.size())/2.0)]) / 2.0;
Can anyone see a problem with this function?
The segfault might be due to memory corruption elsewhere that I'm unaware of, but I want to make sure I'm not making a subtle or careless mistake in the above code before I explore that possibility.
GDB says:
Program received signal SIGSEGV, Segmentation fault.
0x0000000000428ab6 in vecMed (this=0x7fffffffd1b0, vec=...) at ../globals.cpp:834
834 return (copyVec[floor(static_cast<double>(copyVec.size())/2.0)] + copyVec[ceil(static_cast<double>(copyVec.size())/2.0)]) / 2.0;
(gdb) bt
#0 0x0000000000428ab6 in vecMed (this=0x7fffffffd1b0, vec=...) at ../globals.cpp:834
So much errors in the code!
I guess you want:
#include <algorithm>
#include <vector>
double vecMed(std::vector<double> vec) {
if(vec.empty()) return 0;
else {
std::sort(vec.begin(), vec.end());
if(vec.size() % 2 == 0)
return (vec[vec.size()/2 - 1] + vec[vec.size()/2]) / 2;
else
return vec[vec.size()/2];
}
}
First off, if the initial vector is empty, what you're doing is not safe.
Secondly, your logic isn't right in the even case. If copyVec.size() % 2 == 0, it's even, so static_cast<double>(copyVec.size())/2.0 is an integer. So both the floor and ceil are the same thing, so that's probably not what you want to do. Prefer something like:
const int mid = copyVec.size() / 2;
if (copyVec.size() % 2 == 0) {
return 0.5 * (copyVec[mid] + copyVec[mid+1]); // safe unless size == 0
}
else {
return copyVec[mid]; // e.g. if size == 3, return copyVec[1]
}
You don't need floor of ceil, you can do this far more efficiently using integer arithmetic:
return (copyVec[copyVec.size()/2] + copyVec[(copyVec.size() + 1)/2]) / 2.0;
Now this code will do the same as yours but it is easier to read and understand.
Start by trying out some simple cases and some edge cases. In this case you may note that your code does not run correctly for an empty array.
Lets assume you don't see anything suspicious in the code you investigate your best option is to use a debugger. Sometimes using valgrind would also help if you have a stack corruption.
Also you may want to consider using std::nth_element for finding the median of a vector.