Why does finite recursive behaviour cause a crash ? (free(): invalid pointer) - c++

Below is my code just a function called kk that will be recursively called for 10 times so impossible to cause stack overflow, but it crashes with
Error in `./3': free(): invalid pointer: 0x0000000000602100
Who knows the reason??
string kk(string &s)
{
static int i=0;
s+="q";
i++;
cout<<"i="<<i<<endl;
if(i>=10) return s;
kk(s);
}
int main()
{
string s="wer";
cout<<"s="<<kk(s)<<endl;
}

I guess you forgot to put the return keyword in the last line. By putting it, the code is working without errors
string kk(string &s)
{
static int i=0;
s+="q";
i++;
cout<<"i="<<i<<endl;
if(i>=10) return s;
return kk(s);
}
int main()
{
string s="wer";
cout<<"s="<<kk(s)<<endl;
}

C26444 NO_UNNAMED_RAII_OBJECTS this was causing the problem.
On every return, the temporary object was getting created and deleted.
Modified the code like below:
#include <iostream>
#include <cstdlib>
static int i = 0;
void kk(std::string& s)
{
s += "q";
i++;
std::cout << "i=" << i << std::endl;
if (i >= 10) return ;
kk(s);
}
int main()
{
std::string s = "wer";
kk(s);
std::cout << "s=" << s << std::endl;
}
Output:
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
i=10
s=werqqqqqqqqqq

Related

Why does this code work when I remove the return statement in the void function called dfs but returns an inaccurate answer otherwise?

Leetcode q: https://leetcode.com/contest/biweekly-contest-69/problems/longest-palindrome-by-concatenating-two-letter-words/
My Solution:
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isPalindrome(string str){
int n=str.size();
for(int i=0;i<=n/2;i++){
if(str[i]!=str[n-1-i]){
return false;
}
}
return true;
}
int ans=0;
void dfs(string curStr, unordered_map<int,bool> visited, vector<string> &words){
//Snippets for debugging:-
// cout<<curStr<<endl;
// cout<<"Visited map:- \n";
// for (auto i : visited)
// cout << i.first << " is " << i.second
// << endl;
//
// cout<<endl;
//Excluding this gives the correct answer, idk why it dosent work otherwise
//P1:-
// if(visited.size() == words.size()){
// return;
// }
for(int i=0;i<words.size();i++){
if(!visited[i]){
string newStr = curStr + words[i]; //chk?
if(isPalindrome(newStr)){
if(ans<newStr.size()){
ans=newStr.size();
}
}
visited[i]=true;
dfs(newStr, visited, words);
visited[i]=false;
}
}
}
int longestPalindrome(vector<string>& words) {
unordered_map<int,bool> visited;
dfs("", visited, words);
return ans;
}
};
Main Function with invocation:-
int main(){
Solution s1;
vector<string> tc{"lc","cl","gg"};
cout<<"ANS:"<<s1.longestPalindrome(tc);
return 0;
}
I ran my code for this test case shown in main but whenever I exclude the Part Called P1 (or the return statement in the void fn called dfs), it gives the right answer of "6." However, when that snippet P1 is included, it gives an answer "4"
I have no why this is happening. I'm guessing it's something silly but it'd mean a lot if someone could help. Thanks!

throwing an instance with no reason

I have a hard time to debbug this program.
The purpose of the program is to covert a string in a following way.
aaabccddd → abccddd → abddd → abd
Delete the two adjacent element, if they are the same alphabet.
Keep doing this several times, until got a result that cant do it anymore.
If the result dont have any alphabet print out Empty String.
I face a serious problem, my program throwing an instant of 'std::length_error'.
And i check my code. I cant problem in it. Can someone please tell me what happened,
and how to fix it.
This is code:
#include <iostream>
#include <string>
using namespace std;
int main(){
string data;
cin >> data;
for(int i = 0; i < data.size() - 1; i++){
if(data[i] == data[i+1]){
data.erase(data.begin()+i, data.begin()+i+2);
i = -1;
}
}
if(data.size() == 0){
cout << "Empty String";
}else{
cout << data;
}
return 0;
}
There are some imformation about the program.
This is input:
aa
This is execution result:
aa
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::_S_create
--------------------------------
Process exited after 94.29 seconds with return value 3
but sometimes the program can run successfully and
This is input:
aaabccddd
This is execution result:
aaabccddd
abd
--------------------------------
Process exited after 11.27 seconds with return value 0
I dont know what happened. Can someone give me some advice?
When you want to iterate over a container and want to erase something inside the loop, use the following pattern:
for (auto i = container.begin(); i != container.end();) {
if (...some condition...) {
// erase:
i = container.erase(i);
} else {
// keep:
++i;
}
}
The erase() function will return a valid iterator to the item after the range you just deleted.
You do need to use proper iterators for this to work. So in your case, your code should look like:
#include <iostream>
#include <string>
using namespace std;
int main() {
string data;
cin >> data;
for (auto i = data.begin(); i < data.end() - 1;) {
if (i[0] == i[1]) {
i = data.erase(i, i + 2);
} else {
++i;
}
}
if (data.empty()) {
cout << "Empty String\n";
} else {
cout << data << "\n";
}
return 0;
}

Segmentation fault while returning from function in c++

I using stringstream for parsing string, however it is unexpectedly giving segmentation fault while exiting from function.
bool check_if_condition(int a)
{
string polygonString1="19.922379 51.666267 19.922381 51.665595 19.921547 51.665705 19.921218 51.665753 19.920787 51.665815 19.919753 51.665960 19.919952 51.666897 19.920395 51.666826 19.920532 51.667150 19.920830 51.667748 19.920989 51.667905 19.921690 51.667906 19.922141 51.662866 19.922855 51.668696 19.922664 51.668237 19.922610 51.668025 19.922464 51.667451 19.922355 51.666732 19.922379 51.666267";
double buf1; // Have a buffer string
stringstream ssPolygonString1(polygonString1); // Insert the string into a stream
double polygon1[2]; // Create vector to hold our words
int iterPoly1=0;
while (ssPolygonString1 >> buf1)
{
polygon1[iterPoly1]=(buf1);
cout<<"buf1="<<buf1<<"\n";
iterPoly1++;
}
ssPolygonString1.str("");
cout<<"Return true";
return true;
}
main()
{
check_if_condition(1);
}
Can someone please help me understand what is wrong with the function call?
I am using c++11
I ran it on https://www.tutorialspoint.com/compile_cpp11_online.php, it is giving me Bus error (core dumped)
I assume when you say double polygon1[2] you want to create a vector by your comment.
If you use a vector your code will work.
Also when you use a vector make sure you use vector.push_back();
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
bool check_if_condition(int a)
{
string polygonString1 = "19.922379 51.666267 19.922381 51.665595 19.921547 51.665705 19.921218 51.665753 19.920787 51.665815 19.919753 51.665960 19.919952 51.666897 19.920395 51.666826 19.920532 51.667150 19.920830 51.667748 19.920989 51.667905 19.921690 51.667906 19.922141 51.662866 19.922855 51.668696 19.922664 51.668237 19.922610 51.668025 19.922464 51.667451 19.922355 51.666732 19.922379 51.666267";
double buf1; // Have a buffer string
stringstream ssPolygonString1(polygonString1); // Insert the string into a stream
vector<double> polygon1; // Create vector to hold our words
int iterPoly1 = 0;
while (ssPolygonString1 >> buf1)
{
//polygon1[iterPoly1] = (buf1);
polygon1.push_back(buf1); // Add buf1 to vector.
cout << "buf1=" << buf1 << "\n";
iterPoly1++;
}
ssPolygonString1.str("");
//Print vector to show it works!
for (int i = 0; i < polygon1.size(); i++)
{
cout << polygon1.at(i) << endl;
}
cout << "Return true";
return true;
}
int main()
{
check_if_condition(1);
system("pause");
return 0;
}
The error is in the line:
polygon1[iterPoly1]=(buf1);
because the length of vector is 2 and iterPoly is going above 2. So behaviour is unexpected.

Undefined behaviour or may be something with memset

I was trying to save the binary equivalent of a 32 bit number in an array A. For testing my showbits() function , I choosed 8,9 when I came across this thing:
I am facing an unreasonable thing in my code when I am placing memset in the function showbits(),I am geting absurd integers while I expect an output something as
00000000000000000000000000001000
that is the binary equivalent of 8 . While when I place memset in the main() method, it works properly and gives me the right output.Am I going out of bounds(I cannot see it !) .
My code :
SHOWBITS:
void showbits(int A[32],int num)
{
int k=0;
memset(A,0,sizeof(A));
while(num>0)
{
A[k] = num&1;
k++;
num>>=1;
}
return ;
}
Note: I have placed memset in showbits ,and I am getting incorrect answers!
MAIN:
int main()
{
int A[32],i;
showbits(A,8);
for(i=31;i>=0;i--)
printf("%d",A[i]);
return 0;
}
Whole program for testing:
#include<stdio.h>
#include<algorithm>
#include<cstring>
using namespace std;
void showbits(int A[32],int num)
{
int k=0;
memset(A,0,sizeof(A));
while(num>0)
{
A[k] = num&1;
k++;
num>>=1;
}
return ;
}
int main()
{
int A[32],i;
showbits(A,8);
for(i=31;i>=0;i--)
printf("%d",A[i]);
return 0;
}
When I place that memset statement in Main method before showbits() , I am getting correct output!
EDIT
If someone is interested in what I am getting
398420075242008462686872420075219611920941961187434-2205336646196127610926869242
68672826866724200752000202903316219611874341961187478819611565142686716196182637
61961141748268665201000
The A[32] in the method is actually just a pointer to A. Therefore, sizeof is the size of *int. Take the following test code:
void szof(int A[32])
{
std::cout << "From method: " << sizeof(A) << "\n";
}
int main(int argc, char *argv[])
{
int B[32];
std::cout << "From main: " << sizeof(B) << "\n";
szof(B);
return 0;
}
which give the following output:
From main: 128
From method: 8
Thus, the memset sets fewer bits than you think.
You must pass A by reference
void showbits(int (&A)[32],int num)
See here for more details: C++ pass an array by reference
Avi explained the problem in your code already. Another possible solution is to use C++-style arrays, instead of C-style arrays and memset. Then there is no possibility of a memset length error. Also there is no loss of performance.
#include <array>
void showbits(std::array<int, 32> &A, int num)
{
A = {}; // set all entries to 0
// ...
}
int main()
{
std::array<int, 32> A;
// ...
}

Vector push_back causing Unhandled exception

Everything is working until the compiler tries to perform the push_back operation.
in the if condition proper values are being returned.
I have declared items as:
vector<int> items; // inside the header file.
//inside the .cpp file
void MsPs::findnSort()
{
for(int i = 1; i<50 ; i++)
{
string temp = static_cast<ostringstream*>( &(ostringstream() << i) )->str(); // TO convert int i to a string temp
if(findSupport(temp) >= MIS[i])
{
items.push_back(i);
}
}
}
the following error pops up:
Unhandled exception at 0x5052ad4a (msvcp100d.dll) in PrefixScan.exe: 0xC0000005: Access violation reading location 0x3d4cccd1.
PS: I have one more function using the push_back operation and there it's working fine.
Can anyone help me with this?
Even this gives the same error:
void MsPs::findnSort()
{
for(int i = 1; i<50 ; i++)
{
items.push_back(i);
}
}
I think the issue is that the ostringstream is destructed when the static cast returns. Thus your pointer is dangling when str() is called. Try this instead:
void MsPs::findnSort()
{
for(int i = 1; i<50 ; i++)
{
ostringstream blah;
string temp = (blah << i).str();
if(findSupport(temp) >= MIS[i])
{
items.push_back(i);
}
}
}