A memory error with recursion - c++

This is my code. The program gets some point coordinates and it should enumerate all paths (It should be more complicated in future but this is the essence)
#include <iostream>
#include <utility>
#include <vector>
#include <iterator>
#include <algorithm>
#include <cmath>
using namespace std;
struct Point {
Point () {};
Point (const int &x_, const int &y_) : x{x_}, y{y_} {};
int x, y;
};
double distance(const Point &a, const Point &b) {
return sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2));
}
struct Path {
vector<Point> points;
double length;
Path(vector<Point> &p) : points{p}, length{0.0} {};
void add_point(Point &p) {
length += distance(p, points.back());
points.push_back(p);
}
};
vector<Path*> enumerate_paths(vector<Point> &coordinates) {
// assuming coordinates is not empty
vector<Path*> result;
unsigned int size = coordinates.size();
if (size == 1) {
result = {new Path{coordinates}};
return result;
}
vector<Point> coordinates_copy;
vector<Path*> recursion_result;
for(unsigned int i = 0; i < size; ++i) {
cout << "cycle start" << endl << flush;
coordinates_copy = coordinates;
coordinates_copy.erase(coordinates.begin()+i);
// Get results for one coordinate skipped
recursion_result = enumerate_paths(coordinates_copy);
cout << "recursion done" << endl << flush;
// Add the coordinate to each of those results
for_each(recursion_result.begin(), recursion_result.end(),
[&](Path *path) {
path->add_point(coordinates.at(i));});
// Concatenate with previous results
copy(recursion_result.begin(), recursion_result.end(), back_inserter(result));
cout << "cycle end" << endl << flush;
}
cout << "escape recursion" << endl << flush;
return result;
}
int main() {
vector<Point> coordinates = { Point(0,0), Point(1,0), Point(0,1), Point(1,1)};
auto paths = enumerate_paths(coordinates);
cout << "done!" << flush;
}
I believe that the idea of the algorithm is correct, but I'm getting a memory error that I don't understand - double free or corruption (out). I compile with g++ -Wall -std=c++11 without error. What is going on here? Can somebody help?

I can't promise you this is the only problem, but right here:
coordinates_copy.erase(coordinates.begin()+i);
You are eraseing using an iterator from a different vector. Change coordinates.begin() to coordinates_copy.begin().
Also, delete the memory you new ;). Or better yet, switch to smart pointers. Or even forget about pointers entirely and lean on vector's move constructor and the return value optimization instead.

Related

Comparison behavior of ' <' operator

Why is this printing "Popescu" instead of "Ionescu", since "Popescu" > "Ionescu"?
#include <iostream>
using namespace std;
int main(){
char v[3][100] = {"Popescu","Ionescu","Vasilescu"};
if(v[0]<v[1]){
cout << v[0];
}else{
cout << v[1];
}
return 0;
}
Since char[100] doesn't have an operator<, you fall back to operator< for char*. That was not what you intended - it returns the first object in memory. And v[0] definitely precedes v[1].
You want std::string, where operator< is overloaded to do what you want.
Your Initialization is wrong that is why print 'Popescu'
First You need to clear about your array position that is main criteria before start work on your program see my image
see below example:
char always take one character:
#include <iostream>
using namespace std;
int main(){
char v[3][3] =
{
{'p','I','l'},
{'s','e','r'},
{'q','w','x'}
};
cout<< v[0][0]; //print the array2d
return 0;
}
output:
p
First Condition:
#include <iostream>
using namespace std;
int main(){
char v[3][100] = {"p","I","l"};
if(v[0][0]==v[0][0])
{
//cout << v[0]; //when uncomment this line output is p
cout << v[1]; **see here print the i because check the position of array image**
}
else
{
cout << v[1];
}
return 0;
}
output: I //now the position of your array see below
Now the second Condition:
int main(){
char v[3][100] = {"p","I","l"};
if(v[1]==v[1])
{
// cout << v[0];
cout << v[1];
}
else
{
cout << v[1];
}
return 0;
output:
I
If the above criteria Understood then Come To your main problem:
#include <iostream>
using namespace std;
int main(){
char v[3][100] = {"p","I","l"};
if(v[0]<=v[1])
{
cout << v[0];
// cout << v[2];
}
else
{
cout << v[1];
}
return 0;
}
output: p
I hope my answer is understood.

Heap Corruption at class destructor?

I've been trying to figure this out for hours now, and I'm at my wit's end. I would surely appreciate it if someone could tell me when I'm doing wrong.
I wrote a c++ code with class implementing a simple stack, trying to push and pop random stream of characters. It seems to work fine, but at the end of the file, it produces some sort of runtime error:
HEAP CORRUPTION DETECTED: after Normal block....
Since the error occurs at the end of the file, my guess is that there is a problem at deleting the pointer(class destructor). However, I have no idea what is wrong with the destructor I wrote.
Also, after some trial and error, I found out that if I address a bigger number to unsigned integer value iter1 (ex: 80), the runtime error does not occur. Could you explain what is the problem here, and how to bypass it?
stack.h:
class sstack
{
public:
sstack(int length = 256);
~sstack(void);
int sstackPop(char &c);
int sstackPush(char c);
bool isempty();
bool isFull();
protected:
private:
char *sstackBuffer;
int sstackSize;
int sstackIndex; // Initial = -1
};
stack.cpp:
#include "stack.h"
#include <iostream>
using namespace std;
sstack::sstack(int length)
{
sstackIndex = -1;
if (length > 0)
sstackSize = length;
else
sstackSize = 256;
sstackBuffer = new char[sstackSize];
}
sstack::~sstack(void)
{
delete[] sstackBuffer;
}
bool sstack::isempty()
{
if (sstackIndex < 0)
{
cout << "is empty!(isempty)" << endl;
return 1;
}
else
return 0;
}
bool sstack::isFull()
{
if (sstackIndex >= sstackSize)
return 1;
else
return 0;
}
int sstack::sstackPop(char &c)
{
if (!isempty())
{
c = sstackBuffer[sstackIndex--];
cout << sstackIndex << endl;
return 1;
}
else
{
cout << "is empty!(sstackPop)" << endl;
return 0;
}
}
int sstack::sstackPush(char c)
{
if (!isFull())
{
sstackBuffer[++sstackIndex] = c;
return 1;
}
else{
return 0;
}
}
main.cpp:
#include <iostream>
#include "stack.h"
#include <string>
using namespace std;
int main(){
unsigned int iter1 = 5;
unsigned int iter2 = 800;
sstack stackDefault;
sstack stack1(iter1);
sstack stack2(iter2);
char buffer[80];
memset(buffer, 0x00, 80);
char BUFFER[80] = "A random stream of characters";
strcpy_s(buffer, 80, BUFFER);
for (int i = 0; i< strlen(buffer); i++)
{
cout << " stack1: " << stack1.sstackPush(buffer[i]);
cout << " stack2: " << stack2.sstackPush(buffer[i]);
cout << " stackD: " << stackDefault.sstackPush(buffer[i]);
cout << " i : "<< i << endl;
}
cout << "out of Pushes" << endl;
int i = 0;
memset(buffer, 0x00, 80);
while (!stack1.isempty())
stack1.sstackPop(buffer[i++]);
cout << buffer << endl;
getchar();
}
sstackBuffer[++sstackIndex] = c;
Will write past the end of sstackBuffer when the stack only has one element left.
If you consider a stack of size 1. In the first call to push that line would evaluate to:
sstackBuffer[1] = c;
Which is beyond the memory you've allocated.
Be sure you're aware of the difference between pre-increment and post-increment operators. By your code example I would suggest you use post-increment in push and pre-increment in pop.

Pointer Function return value of Struct in Class [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 7 years ago.
I have been attempting to create a function getLocation() that utilizes a pointer to return the value of the struct Location declared in the Character class. I was curious as to the problem with my syntax (or my structure). Knowing that the asterisk * should refer to the value, why is it that my function using an ampersand string& Character::getInventory is able to return the value of that particular index (its return does not need to be converted)?
Trying Location& Character::getLocation() {return position; }
when run results in error C2679: binary '<<': no operator found
Nor
Location*
Which cannot be run as there is no conversion.
I read that the following is likely the most proper because it specifies the scope in which the structure resides, but still results in needing and returning a temporary.
Character::Location* const & Character::getLocation() {return &position; }
Any advice or input would be greatly appreciated, thanks in advance.
Below is my main.cpp, which of course will show the hexadecimal address for Location.
#include <iostream>
#include <string>
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::string;
class Character {
private:
string name;
string inventory[4];
public:
struct Location {
int x; int y;
};
Location position;
public:
void Character::setName(string x) { name = x; }
string Character::getName() { return name; }
void Character::setLocation(int x, int y) {
position.x = x; position.y = y;
}
Location* Character::getLocation() {return &position; }
void Character::setInventory(string(&x)[4]) { for (int i = 0; i < 4; ++i) { inventory[i] = x[i]; } }
string& Character::getInventory(int itemNumber) { return inventory[itemNumber]; }
};
void showUser(Character Character);
int main() {
try {
string items[4] = { "Sword", "Shield", "Potion", "Cloak" };
Character CharacterI;
CharacterI.setName("Some Character");
CharacterI.setInventory(items);
CharacterI.setLocation(1, 30);
cout << "\n" << "Retrieving Character Info..." << "\n" << endl;
showUser(CharacterI);
}
catch (std::exception & e) {
cerr << "\nError : " << e.what() << '\n';
}
system("pause");
return 0;
}
void showUser(Character character) {
cout << "Name : " << character.getName() << endl;
cout << "Location : " << character.getLocation() << endl;
for (int i = 0; i < 4; ++i) {
cout << "Inventory " << i + 1 << " : " << character.getInventory(i) << endl;
}
}
Ok, I think I understand the question better now. The reason why getInventory can successfully return a reference while getLocation does not is because getLocation returns a reference to a temporary variable, which is not good. See the link in #NathanOliver's comment for details. Additionally, to paraphrase a previous comment by #Peter Schneider, an * in an expression dereferences a pointer to return a value, while in a declaration it signifies that a variable will be of pointer type. The two usages are more or less opposites of each other. Example:
int* p = new int; //Declares a pointer to int
int x = *p; //Dereferences a pointer and returns an int
What you need to do is create a member variable to hold the Character's location, then set/get from that variable instead of creating temporaries. You did this already for name and inventory, just keep using that same pattern.
Additionally, whenever you use the Location struct outside of the Character class scope, you need to fully-qualify it with Character::Location.
Example:
#include <iostream>
using namespace std;
class Character {
public:
struct Location {
int x;
int y;
};
Location loc;
void SetLocation(int x, int y) {loc.x = x; loc.y = y;}
Location& GetLocation() {return loc;}
};
int main ()
{
Character c;
c.SetLocation(1,42);
Character::Location l = c.GetLocation();
cout << l.x << endl << l.y << endl;
return 0;
}
Output:
1
42

Trouble with types when passing vector to function in c++

I am starting a c++ class having never done anything in the language before, and I'm pretty confused by vectors.I made a toy example and I don't quite understand why the doubles that I put into a vector become vector's. Here is the code:
#include <iostream>
#include <vector>
using namespace std;
vector<double> a;
void func(vector<double> *);
int main()
{
for (int i = 0; i < 100; i++)
{
a.push_back(double(i));
}
func(&a);
return 0;
}
void func(vector<double> *vec)
{
cout << double(vec[0]) << endl;
return;
}
It ends up giving me this error:
error: cannot convert 'vector' to 'double' without
a conversion operator
and I have no idea what that means. What exactly is happening here and how can I cast a vector into a double?
You don't need to mix using pointers * with std::vector.
Method 1 (not recommended):
Change
cout << double(vec[0]) << endl;
to
cout << double((*vec).at(0)) << endl;
Method 2:
Change
void func(vector<double> *vec)
to
void func(vector<double> vec)
or
void func(const vector<double> &vec)
Change
func(&a);
to
func(a);
The reason for the actual error is more due to a misunderstanding of pointers than vectors . The problem is that you are passing a pointer to a vector. If you want to use the vector itself, then you would do:
cout << (*vec)[0] << endl;
* will dereference the pointer to get the actual vector instance rather than an index into an address which is what you were doing before.
But, as pointed out in the other answer, it is safer just to pass the vector by reference (or better yet, const reference):
void func(const vector<double>& vec)
{
cout << vec[0] << endl;
return;
}
then call as:
func(a);
Another way to use vectors is with a std::vector< TYPE >::const_iterator like this;
#include <iostream>
#include <vector>
double func(std::vector<double>::const_iterator iter);
int main()
{
std::vector<double> vec;
for (double i = 0.0; i < 1; i += 0.1){
vec.push_back(i);
}
std::cout<< func(vec.begin()+3) << " "
<< func(vec.begin()+6) << std::endl;
return 0;
}
double func(std::vector<double>::const_iterator iter){
return *iter;
}
outputs;
0.3 0.6

How to use lambda in for_each?

I am trying to use for_each instead of the normal for loop. However, since I am new to C++11, I am kind of stuck. My intent here is to use for_each and lambda expression together. Any ideas ? I am using visual studio 2010.
Regards,
Atul
Here is the code.
#include "stdafx.h"
#include <algorithm>
#include <memory>
#include <vector>
#include <iostream>
using namespace std;
struct Point
{
union
{
double pt[3];
struct {double X,Y,Z;};
struct {double x,y,z;};
};
Point(double x_,double y_,double z_)
:x(x_),y(y_),z(z_)
{}
Point()
:x(0.0),y(0.0),z(0.0)
{}
void operator()()
{
cout << "X coordinate = " << x << endl;
cout << "Y coordinate = " << y << endl;
cout << "Z coordinate = " << z << endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<Point> PtList(100);
//! the normal for loop
for(int i = 0; i < 100; i++)
{
// Works well
PtList[i]();
}
//! for_each using lambda, not working
int i = 0;
for_each(PtList.begin(),PtList.end(),[&](int i)
{
// Should call the () operator as shown previously
PtList[i]();
});
//! for_each using lambda, not working
Point CurPt;
for_each(PtList.begin(),PtList.end(),[&CurPt](int i)
{
cout << "I = " << i << endl;
// should call the() operator of Point
CurPt();
});
return 0;
}
The third parameter of for_each is a function to apply to each element, not to each index. Otherwise, what would be the point of using that over a traditional loop?
So, instead of an int parameter, it takes a Point parameter. And now there's no reason to capture anything, because a reference to PtList is unnecessary.
// Should make operator() const as it doesn't modify anything
for_each(PtList.begin(),PtList.end(),[](Point const& p)
{
p();
});
Your std::for_each is obviously wrong. The type of the argument to the lamba should be Point, or Point const& depending on what you want to do, and what you're allowed to do.
It should be this:
int count = 0;
for_each(PtList.begin(),PtList.end(), [&](Point const & p)
{
cout <<"No. " << ++count << endl;
p();
});
Make your operator() a const member function.