pointer array in member variable (C++) - c++

I'm currently struggling with a problem with pointer array member variable, Addresses.
The codes below are example codes for my situation. Assume that Addresses always contains at least one element.
// MyClass.h
MyClass{
private:
int size;
Node* root;
Node** Addresses; // Node is custom struct
void saveAddresses(Node* v);
void UpdateAddresses();
public:
MyFunction1() {UpdateAddresses(); cout << Addresses[0] << endl;} // cout for debug
MyFunction2() {UpdateAddresses(); cout << Addresses[0] << endl;} // cout for debug
};
// MyClass.cpp
void MyClass::saveAddresses(Node* v){
static int i = 0;
if (v == nullptr)
return;
saveAddresses(v -> left);
saveAddresses(v -> right);
Addresses[i++] = v;
cout << "SAVED: " << v->key << " in " << v << endl;
}
void MyClass::UpdateAddresses(){
Addresses = new Node*[size];
saveAddresses(root);
}
// in main.cpp
MyClass m = MyClass();
m.MyFunction1(); // It works!
m.MyFunction2(); // SEG FAULT!!
I confirmed (by using cout) that the saveAddresses() function normally saves node pointers into Addresses. Also, MyFunction1() in the main function works well. However, if MyFunction2() is called after function call MyFunction1(), a segmentation fault occurs(Addresses[] becomes nullptr here). I really don't know what the problem is. Please help me!
Note: std::vector is prohibited.

Your UpdateAddresses function will create a new array everytime it is called. If you call it twice, it will always call saveAddresses with a single Node, but the counter will always increased. I see two problems with that:
I don't know what set size to, but it could be that on the second call of saveAddresses you try to set the value for index 1, but it the array is too small (just guessing here).
The first time you call saveAddresses, it will save the node to index 0, which is also the one you read from. The second time you will save the node to index 1, but you will try to read from index 0, which is not initialized.

Related

Data don't insert into an array of pointers

I have my class CompressionAlgorithm from which classes RLE and MTF inherits. I made an array to which I am trying to add these child classes but only first class gets added.
int const size = 2;
CompressionAlgorithm * CA[size];
CA[0] = new RLE();
CA[1] = new MTF();
Both RLE and MTF get initialized but when I am trying to print their name using printall method MTF doesn't get any info printed on console or I am getting an error saying std::bad_alloc.
Print p;
p.printall(*CA, (size));
void Print::printall(CompressionAlgorithm *ca, int size)
{
for (int i = 0; i < size; i++)
{
cout << i+1 << " for ";
cout << ca[i].GetName();
cout << "\n";
}
}
Where am I making a mistake?
You need make function to accept array of pointers not just a pointer:
void Print::printall(CompressionAlgorithm *ca[], int size)
and whil calling you need to call like this:
p.printall(CA, (size));
You don't need to dereference the pointer when passing it to the function; doing so only passes the first element. Additionally the function signature needs to accept an array of pointers, which is what you have.
instead of calling *ca in the printall() call only ca as calling *ca only accesses the first element of the array when not in a loop.

c++ pointer to function and void pointers iteraction resulting in wierd things

Im making a little project at home about genetic algorithm. But im trying to make it generic, so i use pointers to function and void pointers. but i think it might be making some problems.
The main goal of this section of the project is to get a pointer to a function, which return a certain struct. The struct containing a void pointer
and when im trying to view the value of where it points too it isn`t quite right.I suspect that maybe the interaction between these two might be causing me some problems.
details:
struct:
struct dna_s{
int size;
void *dna;
};
population is a class contaning all the population for the process. besides, it contains 2 functions as well, init_func and fitter_func which are both pointers to functions.
pointer to function definition:
typedef dna_s (*init_func_t)();
typedef int (*fitter_func_t)(dna_s);
population class:
class population{
private:
// Parameters
int population_size;
node *pop_nodes;
// Functions
init_func_t init_func;
fitter_func_t fitter_func;
public:
population(int pop_size,init_func_t initialization_func){
// Insert parameters into vars.
this->population_size = pop_size;
this->init_func = initialization_func;
// Create new node array.
this->pop_nodes = new node[this->population_size];
for(int i = 0;i < this->population_size; i++){
dna_s curr_dna = this->init_func();
char *s = static_cast<char*>(curr_dna.dna);
cout << s << endl;
this->pop_nodes[i].update_dna(curr_dna);
}
}
};
You can see that in the constructor im inserting a pointer to function, init_func. this function is generating random words.
init_func:
dna_s init_func(){
string alphanum = "0123456789!##$%^&*ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
char init_s[STRING_SIZE+1] = {};
dna_s dna;
// Generate String
for(int i = 0; i < STRING_SIZE; i++){
init_s[i] = alphanum[rand() % alphanum.size()];
}
cout << "-->" << init_s << endl;
// Insert into struct.
dna.size = STRING_SIZE;
dna.dna = static_cast<void*>(&init_s);
// Return it
return dna;
}
the main function is not so interesting but it might be connected:
int main(){
// Init srand
srand(time(0));
// Parameters
int population_size = 10;
population pop(population_size, init_func);
}
now for the interesting part, whats the problem?
in the init_func the cout prints:
-->e%wfF
which is all good
but in the population class the cout prints:
e%Ω²(
and the wierd thing is the first 2 characters will always be the same, but the other 3 will always be this string Ω²(.
example:
-->XaYN7
XaΩ²(
-->oBK9Q
oBΩ²(
-->lf!KF
lfΩ²(
-->RZqMm
RZΩ²(
-->oNhMC
oNΩ²(
-->EGB6m
EGΩ²(
-->osafQ
osΩ²(
-->3#NQt
3#Ω²(
-->D62l0
D6Ω²(
-->tV#mu
tVΩ²(
Your code has a few lifetime issues. In your dna_S struct:
void *dna;
This is a pointer, it points to an object that exists elsewhere. Then, in your init_func:
dna_s init_func(){
...
char init_s[STRING_SIZE+1] = {};
dna_s dna;
...
dna.dna = static_cast<void*>(&init_s);
...
return dna;
}
init_s is a variable that exists inside init_func, you make dna point to that variable and then leave the function. init_s ceases to exist at this point, dna is pointing nowhere useful when the population constructor gets it, causing undefined behavior.
You could work around that by allocating memory with new char[], like you did for pop_nodes, but you are responsible for deleting that memory when it is no longer used.

C++ problems with pointers while creating Nodes

So I was trying to convert a BST to DLL using some given functions which I had to use. While doing that, I kept getting segmentation faults. As I tried debugging it, I finally came to this. I have written a very simple test script below.
What I knew about pointers is it is passed by reference, as in if I am changing the value/object to which the passed pointer points to, it is reflected in my original calling function.
Why is it that when I create a new Node and then pass the pointer (myf), it works, but when I just pass the pointer and create the new Node inside the function, it shows segmentation fault (myf2)?
If this is because the new node goes out of scope, check the function "myf" again. I have created a new Node which is pointed to by my original node. And the value of this is retained after the function call ends. Doesn't this too go out of scope then?
I have some basic fundamental problems with pointers it appears and this would really help. Thanks
#include<iostream>
using namespace std;
class Node
{
public:
int val;
Node *left;
};
void myf(Node *a)
{
a->left = new Node();
a->left->val = 20;
a->val = 15;
}
void myf2(Node *a)
{
a = new Node();
a->val = 35;
}
int main()
{
Node *a = NULL, *b = NULL;
a = new Node();
a->val = 5;
myf(a);
cout << "New value of a = " << a->val << endl;
cout << "left value of a = " << a->left->val << endl;
myf2(b);
cout << "New value of b = " << b->val << endl;
}
Your problem is, your pointer isn't being set to b, to do so, you'd need to edit myf2 to something like this:
void myf2(Node **a)
{
*a = new Node();
(*a)->val=35;
}
And call myf2 like so:
myf2(&b);
And that should solve your problem, I believe.
Don't think of Node *b as only a pointer, think of it as an integer as well, because that's what a pointer breaks down to, an integer pointing to a space in memory.
So you pass a pointer of the pointer(an integer) to the function.
Another example would be:
void myfunction(int *i) {
*i = 5;
}
int main(int argc, char** argv) {
int x;
myfunction(&x);
cout << x << endl;
return 0;
}
But that's using an actual integer.
Why is it that when I create a new Node and then pass the pointer (myf), it works,
Node *a:
main() makes it point it to a block of memory, you pass that address to myf, you update the memory in that block. It works!
But when I just pass the pointer and create the new Node inside the function, it shows segmentation fault (myf2)?
Node *b:
main() doesn't assign it anything, it is pointing to NULL, myf2() get just the address that is NULL, you create another pointer b (not the same as that in main() ), make it points to some block of memory, but it doesn't update what your original b in main() points to, which is still pointing to NULL. Hence SEGFAULT.
Essentially you are trying two different valid approaches, this is the right way:
Case 1.
main()
{
Node* a = NULL;
a = new Node(); //make 'a' point to some valid block of memory
myf(a); // here you are passing the address of the memory block of type Node
cout << "New value of a = " << a->val << endl; //and this is valid since 'a' points to a valid address
}
void myf(Node *a)
{
a->left = new Node();
a->left->val = 20; // Since the address that you got here is valid, you can make changes here, and in main() Node* a is aware of this address
a->val = 15;
}
Case 2.
main()
{
Node* b = NULL;
myf2(&b); // here since b points to NULL, you have to send the address where this NULL is stored so that the called functon can upadte this NULL to something meaningful
cout << "New value of b = " << b->val << endl; // this is correct, because we changed what 'b' pointed to from NULL to a valid block of memory of type 'Node'
}
void myf2(Node **a) //It is a double pointer here because you need to update what it points to, curently it holds NULL
{
*a = new Node(); // Make it point to a valid address, remember main() has track of 'a',
*a->val = 35; // Now if you make any changes to the blok that 'a' points to, main() will have account of it
}
You need to return the reference of Node *a to which you have dynamically allocated memory..
Node* myf(Node *a)
{
a->left = new Node();
a->left->val=20;
a->val=15;
return a;
}
In main ()
a = myf(a);
previously a in main() is not pointing to memory allocated in myf() function...
Receive your Node ptr by reference as below..
void myf2(Node *&a) //<-- Notice & in function signature.
In your current code, you are passing a (Node*) by value, so, whatever changes done in the function will not reflect outside of function and accessing b->val (null ptr access) will be a segment fault

Linked-List only remembers most recent added object

I have an assignment that requires me to add objects into a linked list. The objects in question are Shapes.
My problem is that I can add objects to the list, but when I try to print them out, only the last added object is printed, the rest are just trash values.
My code looks like this:
Source.cpp:
#include "ShapeList.h"
#include <iostream>
using namespace std;
int main()
{
ShapeList list;
list.add(Rectangle(0,0,2,5));
list.print();
}
I am not allowed to change this code. For example, I am not allowed to send a pointer to the new rectangle, I'm supposed to "deep-copy" it. (I hope I'm using that word right.)
My ShapeList.h looks like this:
#ifndef SHAPELIST_H
#define SHAPELIST_H
#include "Shape.h"
#include "Rectangle.h"
class ShapeList
{
private:
Shape *conductor; //this will point to each node as it traverses the list
Shape *root; //the unchanging first node
public:
ShapeList();
void print();
void add(const Shape &s);
};
#endif
and the header looks like:
#include "ShapeList.h"
#include <iostream>
using namespace std;
ShapeList::ShapeList()
{
cout << "ShapeList created" << endl;
root = new Shape; //now root points to a node class
root->next = 0; //the node root points to has its next pointer set to equal a null pointer
conductor = root; //the conductor points to the first node
}
void ShapeList::add(const Shape &s)
{
cout << "Shapelist's add function called" << endl;
conductor->next = new Shape; //creates node at the end of the list
conductor = conductor->next; //goes to next node
Shape *pShape = s.clone(); //get a pointer to s
conductor->current = pShape; //points current to pShape point
conductor->next = 0; //prevents loops from going out of bounds
}
void ShapeList::print()
{
conductor = root; //the conductor points to the start of the linked list
if(conductor != 0)
{
while(conductor->next != 0)
{
conductor = conductor->next;
cout << conductor->current->width << endl;
}
//cout << conductor->current->width << endl;
}
}
The clone-function is overloaded in all shapes, in this case it's the rectangle's:
Rectangle * Rectangle::clone() const
{
cout << "Rectangle's clone function called" << endl;
Rectangle copiedRect(this);
Rectangle * pCopiedRect = &copiedRect;
return pCopiedRect;
}
Rectangle::Rectangle(const Rectangle *ref)
{
cout << "Rectangle's copy constructor called" << endl;
this->x = ref->x;
this->y = ref->y;
this->width = ref->width;
this->height = ref->height;
}
I know it's alot to read, and I'm sorry. I can remove stuff if it's not needed. I can also add more if you would like.
I have read Alex Allain's tutorial* about linked lists, and a couple of other articles. If anyone has another article, or something like that, to suggest I'm all ears.
http://www.cprogramming.com/tutorial/c/lesson15.html
Rectangle::clone() is invoking undefined behavior. You're returning the address of an automatic variable copiedRect, which falls of scope as soon as the function terminates.
Try this:
Rectangle * Rectangle::clone() const
{
cout << "Rectangle's clone function called" << endl;
return new Rectangle(*this);
}
And your copy-ctor should not even need to be implemented. All the members of Rectangle are trivially copyable. The default should work fine.
Note: I didn't really take the time to dissect your list insertion code, but the above is definitely a problem that needs to be addressed.

Linked list issue with insert

The problem appears with the insert function that I wrote.
3 conditions must work, I tested b/w 1 and 2, b/w 2 and 3 and as last element, they worked.
EDIT;
It was my own problem. I did not realize I put MAXINPUT = 3 (instead of 4). I do appreciate all the efforts to help me becoming a better programmer, using more advance and more concise features of C++.
Basically, the problem has been solved.
Efficiency is not my concern here (not yet). Please guide me through this debug process.
Thank you very much.
#include<iostream>
#include<string>
using namespace std;
struct List // we create a structure called List
{
string name;
string tele;
List *nextAddr;
};
void populate(List *);
void display(List *);
void insert(List *);
int main()
{
const int MAXINPUT = 3;
char ans;
List * data, * current, * point; // create two pointers
data = new List;
current = data;
for (int i = 0; i < (MAXINPUT - 1); i++)
{
populate(current);
current->nextAddr = new List;
current = current->nextAddr;
}
// last record we want to do it sepeartely
populate(current);
current->nextAddr = NULL;
cout << "The current list consists of the following data records: " << endl;
display(data);
// now ask whether user wants to insert new record or not
cout << "Do you want to add a new record (Y/N)?";
cin >> ans;
if (ans == 'Y' || ans == 'y')
{
/*
To insert b/w first and second, use point as parameter
between second and third uses point->nextAddr
between third and fourth uses point->nextAddr->nextAddr
and insert as last element, uses current instead
*/
point = data;
insert(());
display(data);
}
return 0;
}
void populate(List *data)
{
cout << "Enter a name: ";
cin >> data->name;
cout << "Enter a phone number: ";
cin >> data->tele;
return;
}
void display(List *content)
{
while (content != NULL)
{
cout << content->name << " " << content->tele;
content = content->nextAddr;
cout << endl; // we skip to next line
}
return;
}
void insert(List *last)
{
List * temp = last->nextAddr; //save the next address to temp
last->nextAddr = new List; // now modify the address pointed to new allocation
last = last->nextAddr;
populate(last);
last->nextAddr = temp; // now link all three together, eg 1-NEW-2
return;
}
Your code works fine on my machine (once the insert(()) statement is "filled in" properly as explained in the code comment). The insertion works in all positions.
Something else, though: I initially had a look at your insert function. I thought I'd give you a hint on how to make it a little shorter and easier to understand what's going on:
void insert(List *last)
{
// create a new item and populate it:
List* new_item = new List;
populate(new_item);
// insert it between 'last' and the item succeeding 'last':
new_item->nextAddr = last->nextAddr;
last->nextAddr = new_item;
}
This would be preferable because it first creates a new, separate item, prepare it for insertion, and only then, when this has worked successfully, will the function "mess" with the linked list. That is, the linked list is not affected except in the very last statement, making your function "safer". Contrast this with your version of insert, where you mix code for constructing the new item with the actual insertion. If something goes wrong inside this function, chances are far higher that the linked list is messed up, too.
(What's still missing btw. is a initial check whether the passed argument last is actually valid, ie. not a null pointer.)
P.S.: Of course you could just use a standard C++ std::list container instead of building your own linked list, but seeing that you tagged your question beginner, I assume you want to learn how it actually works.
step one should be to make the list into an object instead of just keeping a bunch of pointers around in main(). you want an object called List that knows about it's own first (and maybe last) elements. it should also have methods like List.append() and List.insert().
your current code is nigh unreadable.
Use a std::list, unless this is homework, in which case it needs tagging as such.
In my experience, I have learned to start small and test, then build up. I'll guide you through these steps.
BTW, a linked list is a container of nodes. So we'll start with the node class first.
Minimally, a node must have a pointer to another node:
#include <iostream>
#include <cstdlib> // for EXIT_SUCCESS
#include <string>
using std::cout;
using std::endl;
using std::cerr;
using std::cin;
using std::string;
struct Node
{
// Add a default constructor to set pointer to null.
Node()
: p_next(NULL)
{ ; }
Node * p_next;
};
// And the testing framework
int main(void)
{
Node * p_list_start(NULL);
// Allocate first node.
p_list_start = new Node;
// Test the allocation.
// ALWAYS test dynamic allocation for success.
if (!p_list_start)
{
cerr << "Error allocating memory for first node." << endl;
return EXIT_FAILURE;
}
// Validate the constructor
ASSERT(p_list_start->p_next == 0);
// Announce to user that test is successful.
cout << "Test successful." << endl;
// Delete the allocated object.
delete p_list_start;
// Pause if necessary.
cin.ignore(100000, '\n'); // Ignore input chars until limit of 100,000 or '\n'
return EXIT_SUCCESS;
}
Compile, and run this simple test. Fix errors until it runs correctly.
Next, modify the tester to link two nodes:
int main(void)
{
Node * p_list_start(NULL);
Node * p_node(NULL); // <-- This is a new statement for the 2nd node.
//...
// Validate the constructor
ASSERT(p_list_start->p_next == 0);
// Allocate a second node.
p_node = new Node;
if (!p_node)
{
cerr << "Error allocating memory for 2nd node." << endl;
// Remember to delete the previously allocated objects here.
delete p_list start;
return EXIT_FAILURE;
}
// Link the first node to the second.
p_list_start->Link_To(p_node);
// Test the link
ASSERT(p_list_start.p_next == &p_node);
//...
// Delete the allocated object(s)
delete p_list_start;
delete p_node;
//...
}
Compile with the modifications.
It failed to compile, undefined method: Node::Link_To
Not to worry, this is expected. Show us the compiler is working. :-)
Add the Link_To method to the Node structure:
struct Node
{
// ...
void Link_To(const Node& n)
{
p_next = &n;
return;
}
//...
};
Compile and run. Test should pass.
At this point the linking process has been validated. Onto adding content to the node.
Since the Node object has been tested, we don't want to touch it. So let's inherit from it to create a node with content:
struct Name_Node
: public Node // Inherit from the tested object.
{
std::string name;
std::string phone;
};
If you haven't learned inheritance yet, you can append to the existing node:
struct Node
{
//...
std::string name;
std::string phone;
}
At this point you can add functions for setting and displaying content. Add the testing statements. Run and validate.
The next step would be to create two content nodes and link them together. As you build up, keep the testing code. Also, if stuff works you may want to put the functionality into separate functions.
For more information on this process, check out Test Driven Development.