Returning pointer to global array from function - c++

I am not experienced enough in C/C++ programming, so I am asking for an explanation.
I have global array declared as following. ASAK it is located in seperate memory part of initialized global memory in context of process memory.
Sensor sensorsArray[SENSORS_COUNT] = {dhtTempSensor, dhtHumSensor, dallasTempSensor, waterLevelSensor};
I need to find element in this array and return pointer to it (because I am going to change its value). I have written such function.
Sensor* getSensorById(uint32_t id) {
for (int i = 0; i < SENSORS_COUNT; i++) {
Sensor* current = &sensorsArray[i];
if (current->sensorId == id) {
return current;
}
}
}
Will it work properly, I am not sure about current pointer, it is allocated on the stack so it is in function scope, will it be poped from the stack after function ends ? Or it will work properly.
I mean not pointer(address of array element which is taken using &sensorsArray[i]), but current pointer variable which contains address of erray element, will it be poped or not.
Please suggest best way how to do in such situation.
Thx.

You aren't covering all the possible returning cases of the function, namely, the case when the id does not match with any of the ids of the array.
Currently the pointer will return the last element of the array if there is no match.
You could correct that by defining the pointer Sensor* sensor_found = nullptr outside the for loop such that if there is no sensor found the return value is still valid, i.e. nullptr and assigning the found value of current to sensor_found, only if there is a match.
Sensor* getSensorById(uint32_t id) {
Sensor* sensor_found = nullptr;
for (int i = 0; i < SENSORS_COUNT; i++) {
Sensor* current = &sensorsArray[i];
if (current->sensorId == id) {
sensor_found = current;
break;
}
}
return sensor_found;
}
If the id found return current, otherwise, if there is no match return nullptr.

you want to make sure that the function has a valid return statement on its every execution path. In you current implementation if the id is not matched then the return value of Sensor* is not set and will contain random bytes. One wau to deal with this situation is to return the nullptr to indicate that the Sensor was not found. Other than that, ythe function will work properly.
Sensor* getSensorById(uint32_t id) {
for (int i = 0; i < SENSORS_COUNT; i++) {
Sensor* current = &sensorsArray[i];
if (current->sensorId == id) {
return current;
}
}
return nullptr; // id not matched
}

Your code is fine (as the comments suggest). The reason why you don't need to worry about the current pointer becoming invalid is because the memory that it points to (ie, the global array) stays valid beyond the scope of the function. Just because you happen to create a pointer (and remember, a pointer is really just a number that corresponds to some place in memory) to that memory doesn't mean that it becomes invalid when used elsewhere.
When you say Sensor *current = &sensorArray[i];, then if sensorArray[i] is stored at, say, position 0x10 in memory, then current = 0x10, and no matter where it is used, then sensorArray[i] will still be at memory location 0x10. When you assign a value to current, you are not copying the value from the sensor, you are merely getting a pointer to it.

Related

Declaring any new variable changes pointer address for unknown reason

I am writing an auction program for a class project and one of the features I was trying to implement was a hash table to make searching for auction items by name efficient. I set it up in node format so that you can chain nodes together if their hash value lines up with another item that already exists.
The main problem that I cannot seem to figure out is how some pointer values are changing when I don't think I have done anything to them. I stepped through each line of this program keeping an eye on the Red highlighted areas in the attached screenshots to see when the data changes. In case #1 the data was intact and able to be accessed. However, in case #2 where I simply declare an additional variable (int i = 0;) suddenly the data passed into the function appears to point to a different memory location (0xcccccccc) which from what I understand is another version of null? This is the same no matter what variable type I have tried to declare whether it be an int, const char*, string, etc it all reacts like the second screenshot.
Does anyone know why the program would be doing this? Are there any other troubleshooting tips? Is this a common error and how should I avoid it in the future and for this project?
I can provide a complete code if needed. I appreciate any help you can provide.
Image 1: No additional variable declared, data in tact as expected
Image 2: integer variable declared, data at ->next suddenly changed. This appears to be this way from the start of the function.
Update: I created an MRE as suggested in a comment, the same error can be reproduced using this code.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
class AuctionItemBidsMaxHeap {
string name = "test";
public:
const char * getItemName() {
return name.c_str();
}
};
class AuctionItemHashTable {
private:
struct Node {
AuctionItemBidsMaxHeap* AuctionItem;
Node* next = nullptr;
};
Node* itemArray;
int capacity = 50;
int generateHashKey(string auctionItem) {
return 11;
}
public:
AuctionItemHashTable() {
//Create the array of X amount of different possible storage locations
Node emptyNode;
emptyNode.AuctionItem = nullptr;
emptyNode.next = nullptr;
itemArray = new Node[capacity];
for (int i = 0; i < capacity; i++) {
itemArray[i] = emptyNode;
}
}
~AuctionItemHashTable() {
delete itemArray;
}
void insertItem(AuctionItemBidsMaxHeap* auctionItem) {
//Check to see if this item already exists
int key = generateHashKey(auctionItem->getItemName());
Node newAuctionItem;
newAuctionItem.AuctionItem = auctionItem;
newAuctionItem.next = nullptr;
//Check to see if anything has been inserted there yet
if (itemArray[key].AuctionItem == nullptr) {
itemArray[key] = newAuctionItem;
}
else {
//WE have to make room in the semi-linked list
Node holder;
holder.AuctionItem = itemArray[key].AuctionItem;
holder.next = itemArray[key].next;
newAuctionItem.next = &holder;
itemArray[key] = newAuctionItem;
}
}
AuctionItemBidsMaxHeap* getAuctionItem(const char* itemName) {
int key = generateHashKey(itemName);
//Loop through all items in location
Node* currentNode = &itemArray[key];
if (currentNode == nullptr) {
return nullptr;
}
else {
if (currentNode->AuctionItem->getItemName() == itemName) {
cout << "Match" << endl;
}
while (currentNode->next != nullptr && currentNode->next != (void*)0xcccccccc) {
int i = 0;
if (currentNode->next->AuctionItem->getItemName()[0] == 'M') {
cout << "M Matched" << endl;
}
while (currentNode->next->AuctionItem->getItemName()[0] != 'e') {
//cout << currentNode->next->AuctionItem->getItemName()[i];
}
currentNode = currentNode->next;
}
//There was an item stored at this location, lets see which one it is
//void* p = (void*)0xcccccccc; //Creating a pointer since for some reason my final pointer gets changed to another type of null character upon passing it to a function
//cout << currentNode->AuctionItem->getItemName() << endl;
//while (currentNode->next != nullptr && currentNode->next != p) {
//cout << currentNode->AuctionItem->getItemName() << endl;
//currentNode = currentNode->next;
//}
return currentNode->AuctionItem;
}
}
};
int main()
{
/**Creating MaxHeap of one bid**/
AuctionItemBidsMaxHeap myBidTest;
AuctionItemBidsMaxHeap myBidTest2;
/**Creating Auction Item Hash Table**/
AuctionItemHashTable auctionItems;
auctionItems.insertItem(&myBidTest);
auctionItems.insertItem(&myBidTest2);
const char* myInput = "test";
auctionItems.getAuctionItem(myInput);
}
First a rant: Why is it that classes still teach pointers in C++? There are MUCH better ways to do this than Node*.
Your code contains several errors, but the most important one is here:
//WE have to make room in the semi-linked list
Node holder;
holder.AuctionItem = itemArray[key].AuctionItem;
holder.next = itemArray[key].next;
newAuctionItem.next = &holder; ////<<< ERROR HERE
itemArray[key] = newAuctionItem;
You create a temporary variable on the stack Node holder; This variable will be destroyed as soon as you leave the function.
But you take a pointer to this variable here
newAuctionItem.next = &holder;
IOW: Your list contains pointers to objects that no longer exist.
&holder is the address of the variable holder. As soon as holder goes out of scope, the contents of it will be destroyed. But newAuctionItem.next and as a consequence also itemArray[key].next will still point to the memory, where holder used to be.
This is what is called a dangling pointer.
I stopped reading your example, but it is also pretty dangerous to accept pointers to AuctionItems in your insert method. When you are using pointers here, you MUST MAKE SURE, that the actual objects remain valid for as long as they are in the list.
Or, to put it the other way round: You must remove them from your list before they get destructed. And we humans are not made to "make sure". We make errors, so it is better to write code where you cannot make an error like this (i.e. avoid pointers in the first place).
Another error: You are creating an array with itemArray = new Node[capacity];, but you are deleting it with delete itemArray;. When you are using new to create an array, you must use delete[] itemArray to delete it. See here delete vs delete[] operators in C++
A general note: DO NOT USE POINTERS AT ALL (unless you have to). Pointers are an advanced C++ concept.
You could use shared_ptr<> instead. This will take away the burdon of freeing the memory.
For your itemArray you could use std::vector<> instead of allocating an array with new[]; etc...
There are many good and easy to use classes in the C++ library, which will help you a lot writing safer and cleaner code.
Learning C++ is (at least) as much about learning the std Library as about learning the syntax and statements. std::vector<AuctionItemNodes> IS C++.

pointer returned to an object turns null after function returns address

I am new to CPP and I am writing a program as an assignment to simulate a train path system that includes destinations and starts using object oriented programming .
I have 2 classes as shown below (there is a a passenger class but it is not relevant ) :
class Train
{
public:
int cooldown_time;
int travel_time;
int time_since_movement;
int id;
class Station *start;
class Station *destination;
vector<Passenger *> current_passengers;
string status;
void add_train(vector<string> commands, vector<Station> stations, vector<Train> &trains)
{
travel_time = stoi(commands[THIRD_PART + 1]);
cooldown_time = stoi(commands[THIRD_PART + 2]);
status = TSTATUS1;
start = station_search(stations, commands[SECOND_PART]); // this is where the problem happens
destination = station_search(stations, commands[THIRD_PART]);
id = stations.size();
}
};
class Station
{
public:
int tuffy_price;
string city_name;
vector<Passenger *> current_passengers;
vector<Train *> current_trains;
int id;
void add_station(vector<Station> &stations, vector<string> &commands)
{
tuffy_price = stoi(commands[THIRD_PART]);
city_name = commands[SECOND_PART];
id = stations.size();
}
};
I have a search function dedicated to finding the start and destination based off a command that user enters for example :the user enters "add_train cityname1 cityname2 <cooldown_time> <travel_time>". my program detects the city names and searches a vector I have named stations with a key that is the city name and returns a pointer (because of the complications in memory behavior in a function , i set it to pointer) to that station-object .
the function is as below :
Station *station_search(vector<Station> stations, string key)
{
Station *dummy;
for (int i = 0; i < stations.size(); i++)
{
if (stations[i].city_name == key)
{
return &stations[i];
}
}
return dummy;
}}
my problem is with my search function's weird behavior , when I debug the program I see the function find the correct station object and return a pointer to it ,but when the execution returns to the constructor function it randomly (maybe not randomly ) turns the first pointer relating to the start station to null and replaces the values inside with garbage ones.
but after the function searches for the destination station it does not do this and the execution is correct.
Could someone explain why this error is occurring?
My guess is that I have not understood local variables and pointer returns well enough and I have committed a rookie mistake somewhere but I don't seem to find it .
PS: I did not include the full code as it's too long I can include it by attaching a file ,comment down if it's necessary.
Station *station_search(vector<Station> stations, string key)
If you take a closer look here, you will see that the stations parameter is passed by value, which means that after this function returns, this stations parameters will get destroyed. It will be no more. It will cease to exist. It will become an ex-parameter.
However this station_search returns a pointer to some value in this vector. Therefore, rules of logic dictate that it will return a pointer to a destroyed object. Attempting to dereference that pointer, in any way, becomes undefined behavior.
Your other class methods receive parameters by reference, so you must already understand the difference between passing parameters by value vs. by reference, so you should simply do the same here.
Here you are passing a copy of the vector, which is destroyed when the function returns. Additionally, if the key is not found an uninitialized pointer is returned.
Station *station_search(vector<Station> stations, string key)
{
for (Station &station : stations)
{
if (stations.city_name == key)
{
// Pointer becomes invalid when you leave.
// Accessing this pointer will cause undefined behavior.
return &station;
}
}
// This would always cause undefined behavior as dummy was not initialized.
return nullptr;
}
You should pass in a reference and initialize dummy:
Station *station_search(vector<Station> &stations, string key)

Pointer Help in C++

I am new to c++(have a java background) and thus pointers are sort of new to me. I am dealing with an array of pointers where each index points to an object on the heap as so:
Deck::Deck()
{
seed = rand()%100; //this will be used in shuffle method
srand(seed);
for(int i=0;i<deckSize;i+=3) //deckSize=12 in this case, p defined as CardTypes* p[deckSize]
{
p[i]= new Infantry();
p[i+1] = new Artillery();
p[i+2] = new Cavalry();
}
}
All 3 of these classes are subclasses of the class CardTypes(which was only created so I could store diff types in an array).
class CardTypes
{
public:
virtual string getCard() = 0;
virtual ~CardTypes() {};
};
class Infantry: public CardTypes
{
const string name = "Infantry";
public:
string getCard(); //this simply returns "name" so that I can differentiate each object in the array by a data value
};
class Artillery:public CardTypes
{
const string name= "Artillery";
public:
string getCard();
};
class Cavalry:public CardTypes
{
const string name = "Cavalry";
public:
string getCard();
};
Although not a great way to do it, I have created another array of pointers(CardTypes* s[deckSize) which copies pointers from p into s randomly(thus mimicking a shuffle in a deck of cards):
void Deck::shuffle() //this is the method that puts objects in s to be grabbed in draw()
{
int j = 0;
int k = 1;
int l = 2; //initial setup(index 0 will have Infantry, index 1 will have Artillery and index 3 will have Cavalry and this pattern continues throughout p)
int n = rand()%3 + 1; //gives random # between 1 and 3 1=infantry,2 = artillery,3 = cavalry
int i=0; //counter for loop
while(i<deckSize)
{
n = rand()%3+1;
if(n==1)
{
if(j>9) //means no more infantry cards as due to pattern of p
infantry cards stop after index 9
{
continue; //used to reset loop foranother iteration(will get random number,I know this is bad for time complexity)
}
else
{
s[i] = p[j]; //copy "Infantry" pointer to s
j+=3;
i++;
}
}
else if(n==2)
{
if(k>10)//means no Artillery cards due to pattern in p
{
continue;
}
else
{
s[i] = p[k];//copy "Artillery" pointer to s
k+=3;
i++;
}
}
else
{
if(l>11) //means no more cavalary cards due to pattern in p
{
continue;
}
else
{
s[i] = p[l]; //copy "Cavalry" pointer to s
l+=3;
i++;
}
}
}
}
Now my issue is i am trying to create a draw method that grabs a pointer from s and returns it. My program completely crashes when I attempt this and I am not sure why:
CardTypes* Deck::draw() //draws a card from the deck and returns it
{
CardTypes* card = s[deckSize];
delete s[deckSize];//clear heap
s[deckSize] = NULL;//remove what pointer was pointing too (as card has been drawn)
deckSize--;
return card;
}
I then attempt to call this method:`
int main()
{
Deck d1;
d1.shuffle(); //this works
d1.getCurrentDeck();//this works, just prints out each objects getCard() method in s
CardTypes* card = d1.draw();//does not cause a crash
cout<<"Card:"<<card->getCard() <<"\n";//crashes here
}
This issue is probably due to my inexperience with pointers but any help would be appreciated. Also note I delete the arrays after I am done with the program using delete [] p and delete [] s, I have not included this in the code as it is not of issue right now.
You are struggling with pointer ownership. You understand that in C++ one must delete a pointer when it is no longer needed, but in Deck::draw you delete a pointer when it is still needed.
CardTypes* Deck::draw()
{
CardTypes* card = s[deckSize]; // s and card point to same allocation
delete s[deckSize]; // boom! card points to garbage.
s[deckSize] = NULL;
deckSize--;
return card;
}
You can use raw pointers, but you need to do it with a lot of coding maturity and deliberation.
Or you can say Smurf it and protect yourself from accidents like this with smart pointers. What is a smart pointer and when should I use one?
std::unique_ptr bundles ownership of a pointer. Only one std::unique_ptr is allowed at a time. You can't copy it. It as to be moved everywhere, transferring ownership from one holder to the next. But in the end there can be only one. You have to go out of your way to be stupid with a unique_ptr. Making five unique_ptrs and pointing them all at the same pointer, yeah you can do that. Put a self-destructing Automatic variable in a unique_ptr, yeah you can do that (and sometimes you do, but with a custom deleter that does nothing).
unique_ptr is the owner of the pointer. Whoever has the unique_ptr is owner by proxy because as soon as they get rid of the unique_ptr, the pointer goes with it.
Let's take a look at what we can do with a std::unique_ptr<CardTypes> to corral these wild pointers. If s is an array of unique_ptrs, std::unique_ptr<CardTypes> s[MAX_DECK_SIZE];, draw becomes
std::unique_ptr<CardTypes> Deck::draw()
{
std::unique_ptr<CardTypes> card = std::move(s[deckSize]);
// delete s[deckSize]; don't. Card now owns the card
// s[deckSize] = NULL; handled by moving ownership
deckSize--;
return card;
}
This can be simplified to
std::unique_ptr<CardTypes> Deck::draw()
{
return std::move(s[deckSize--]);
}
decksize-- is a post decrement so it happens after and the rest of the work is managed by the unique_ptr when it is moved out of s;
Sadly this means
s[i] = p[j];
ain't so easy anymore. You need
s[i] = std::move(p[j]);
But only if p no longer needs its jth element, because s[i] owns it now, baby.
Too little information has been provided in the question to wrangle this properly, but...
It's very possible that you could keep p full of unique_ptrs and load s with raw pointers whose lifespan is governed by p and pass s's pointers around naked and free without ever deleteing them because you know p has your back. So long as you keep p around longer than s and whoever s gives pointers to. It all comes back to ownership and in this case p owns all the Cards.
That turns
s[i] = std::move(p[j]);
into
s[i] = p[j].get();
and draw into
CardTypes * Deck::draw()
{
return s[deckSize--];
}
and makes life really, really easy.
Your problem is you are deleting the instance and, after that, you want to use it.
You are creating many instances:
for(int i=0;i<deckSize;i+=3) //deckSize=12 in this case, p defined as CardTypes* p[deckSize]
{
p[i]= new Infantry();
p[i+1] = new Artillery();
p[i+2] = new Cavalry();
}
The size of your array is determined by the variable deckSize.
In your function Deck::draw() your have some errors:
You are set a pointer of an instance of CardType with this code: CardTypes* card = s[deckSize]; But the array s has an index base 0, so s[deckSize]is accessing another memory sector that is not assigned to array s (Could a Memory Access Violation). use s[deckSize-1] instead of s[deckSize]..
You are release the memory that was assigned to pointer card and this pointer is returned to be used outside the function, which try to use this instance but is doesn't exist any more. So the memory which card and s[deckSize] share is released. Don't forget that s[deckSize] could raise a Memory Access Violation.
Check your code:
CardTypes* Deck::draw() //draws a card from the deck and returns it
{
CardTypes* card = s[deckSize-1]; //Assign the pointer to card.
delete s[deckSize-1];//DELETE THE INSTANCE (The memory that
return card; //The card points to a memory previously released.
}
Here is the moment that you are trying to use an unallocated:
CardTypes* card = d1.draw();//Get the pointer to s[deckSize-1]
cout<<"Card:"<<card->getCard() <<"\n";//crashes here
UPDATE:
Answer your comment, You can do this:
1.- Get the referencer to instance: CardTypes* card = s[deckSize-1];.
2.- Set the slot of your array in NULL and decrease the index:
s[deckSize-1]=NULL;
deckSize--;.
3.- Return de reference saved in card to upper level: return card;.
4.- Use the reference returned as you need it:
CardTypes* card = d1.draw();
cout<<"Card:"<<card->getCard() <<"\n";.
5.- Finally, delete de instance once you have finished to use it, for example just after the invocation of getCard():
cout<<"Card:"<<card->getCard() <<"\n";
delete card;
It's important to say that you decide where and when reserve, use and release the memory; just keep in mind to do it in an organized way and apply best practices, like these:
https://www.codeproject.com/Articles/13853/Secure-Coding-Best-Practices-for-Memory-Allocation
http://www.embeddedstar.com/technicalpapers/pdf/Memory-Management.pdf

C++ MFC - CMapPtrToPtr - SetAt and Lookup

I'm using MFC C++ for my Windows Application, where I need to persist (not in a Database) some data using CMapPtrToPtr. The key is a pointer to a structure (let's call it SIGNAL_DATA* pSignal) and the value is a double array.
The problem is, when I read the value again, it is giving me a garbage/undefined value (not the value I stored).
Sample Code:
In the header file:
CMapPtrToPtr prevZoomValsMap;
double zoomPreVals[2];
In the implementation class:
void funktion1()
{
if(ersteSchleife == FALSE) //first time, it is false
{
SIGNAL_DATA* pSelectedSignal; //properly initialised. verified in debug mode
zoomPreVals[0] = zoomMinSkal; //valid double values. verified in debug mode
zoomPreVals[1] = zoomMaxSkal;
prevZoomVals.SetAt((void*) pSelectedSignal, (void*) zoomPreVals);
ersteSchleife = TRUE;
}
else
{
funktion2();
}
}
In another function, when I read the value as below, I'm getting garbage values.
void funktion2()
{
void *zoomValuesTemp_;
prevZoomValsMap.Lookup((void*) sigTemp, zoomValuesTemp_);
double *zoomValuesTemp = (double*)zoomValuesTemp_;
if(zoomValuesTemp == NULL) //verified in debug mode. never becomes NULL.
{
int aRTD = 10; //dummy assignment.
}
double aValue = zoomValuesTemp[0] ; //Access Violation
}
Assuming that the code you provide is running in a function, we get
void store_it(SIGNAL_DATA* pSelectedSignal)
{
double zoomPreVals[2] = {zoomMinSkal, zoomMaxSkal}; //also, initialised.
prevZoomVals.SetAt((void*) pSelectedSignal, (void*) zoomPreVals);
}
If this is what you have, then you are storing the address of a local variable (zoomPreVals) in the map. Since zoomPreVals is destroyed at the end of the function, the pointer to zoomPreVals becomes invalid. You cannot use this pointer anymore.
You must make sure that the pointer stays valid, so you can for example allocate a new structure with new and store the pointer in the map - don't forget to free the data later.
You might also consider using CMap<SIGNAL_DATA*, SIGNAL_DATA*, MYDATA, MYDATA&> and store objects instead of pointers as map values.
You might also consider using STL classes like map and unique_ptr.
Your retrieval code is not correct. You should not cast to match the function parameters, but pass the right parameters.
void *zoomValuesTemp_;
prevZoomVals.Lookup((void*) sigTemp, zoomValuesTemp_);
double *zoomValuesTemp = (double*)zoomValuesTemp_;

Queue class not dequeuing correctly

i asked a similar question here yesterday and i corrected some of the issues but the main one still persists.
Im enqueuing and dequeueing Position objects into a Position queue.As i enqueue 2 different Position objects, and dequeue both back out, both Position objects that are returned have the same value as the 2nd object put in. When i check the values that have been enqueued inside the enqueue function they are correct.I dont understand how this wont work as ive worked out the logic and used the dequeue algorithm verbatim from a book;
The Position class has 3 array based stacks as private members
struct Posnode
{
Position *pos;
Posnode *next;
};
class Position
{
private:
Posnode *front,*back,header; //front = back = &header;
Pegs A,B,C;
Position::Position(int num): A(num), B(num), C(num)
{
front = back = &header;
A.assignpeg(num);//assigning 1 to n to each Peg
B.assignpeg(num);
C.assignpeg(num);
}
#include "Pegs.h"
#include "Position.h"
int main ()
{
Position pos(4), intial(3),p,m,n;
intial.geta();//poping Peg A stack
pos.getc();//poping Peg c stack
p.enqueue(intial);
p.enqueue(pos);
p.dequeue(m);//position 'pos' is returned rather than intial
p.dequeue(n);//position 'pos' is returned
cin.get();
return 0;
}
void Position::dequeue(Position&)
{
Position p;
Posnode *ptr=front->next;//front points to an empty node wi
p = *ptr->pos;//assigning the position in ptr to p
front->next = ptr->next;
if (back == ptr) {//if im at the end of the queue
back = front;
}
delete ptr;
return ;
}
void Position::enqueue(Position n)
{
Posnode *ptr = new Posnode;
ptr-> pos = &n;//copying Position n calls Pegs operator =
back->next = ptr;//values that are enqueued check back ok
back = ptr;
return;
}
Pegs& Pegs::operator=(const Pegs & ori)//Pegs copy contructor
{
top=-1;
disks = ori.disks;
peg = new int[disks];
int element=0,g=-1,count=0;
while (count <= ori.top)//copying elements if there are any in ori
{
++count;
element=ori.peg[++g];
push(element);
}
return *this;
}
Sorry mate, but there are many problems with your code. Some of them seem to be copy/paste errors, but other show lack of C++ understanding. I'll focus on the latter first.
The member function void Position::enqueue(Position n) copies all passed arguments by value. So what happens when you call it? The parameter is copied and inside the function you are dealing with this copy that will be disposed when the function's scope ends. So assignemtn ptr-> pos = &n will assign an address of a temporary object to pos. Data at the address of disposed object may still be valid for some time, as long as nothing writes over it, but you should never ever depend on this behaviour. What you should do is you should pass the parameter by reference, i.e. change the declaration to void Position::enqueue(Position& n). That way the actual object will be passed, not a automatic copy.
If you don't specify a name for an argument like in void Position::dequeue(Position&), you won't have access to it. Inside this function you create a local variable p and then assign the result to it. But because p is local it will be disposed when the function returns. Needless to say, the parameter that you pass to this function is inaccessible because it's unnamed. What you should do is you should declare the function like that: void Position::dequeue(Position& p).
As a good advice: you should do better job with isolating your case. For example, are Pegs connected in any way to the problems you are having? Also avoid declarations like Posnode *front,*back,header - in most cases they make code harder to read. And did you notice that your code has #includes inside class body?! You should never to that, except for times when you exactly know what you are doing. #include directives should be usually put in the first lines of a source file.