473,410 Members | 1,977 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,410 software developers and data experts.

dynamic memory in c++

While working on dynamic memory in c++ I noticed that values of my previous variables were changing whenever i invoke a loop.

for the following code::
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. using namespace std;
  5.  
  6.  
  7. template <class T>
  8. class Node {
  9. private:
  10.  
  11. public:
  12.     T item;
  13.     Node<T>* next;    
  14.     Node(T a,Node<T>* c) {item = a;next = c;};
  15.     void set_item(T a)  {item = a;};
  16.     void set_item(Node<T>* c) {next = c;};    
  17. };
  18.  
  19.  
  20. template <class T>
  21. class List {
  22. private:
  23.         Node<T>* head;
  24.         Node<T>* tail;
  25.         int length;
  26. public:
  27.         List() {head = NULL;tail = NULL;length=0;};
  28.         int size();
  29.         bool empty();
  30.         void push_back(T);
  31.         void push_front(T);
  32.         void insert(int,T);
  33.         void print();
  34.         bool ismember(T);//pain
  35.  
  36.         // Member functions to
  37.         // interface with list
  38. };
  39.  
  40. template <class T>
  41. void List<T>::push_front(T a){
  42.     length++;                  //initially head->x1->null
  43.     Node<T>b(a,head);          //now head->new entry->x1->null
  44.     head = &b;
  45.     if(length == 1) tail = &b;
  46.     cout<<"look push front gives"<<(*head).item<<endl;
  47.     }
  48.  
  49. template <class T>
  50. void List<T>::print(){
  51.         cout<<"here"<<(*head).item<<endl;
  52.     Node<T> *mynode;
  53.     mynode = head;
  54.     cout<<"here   "<<(*head).item<<endl;
  55.     for(int i = 0;i < length;i++,mynode = (*mynode).next)
  56.     {cout<<i<<"th entry is "<<(*mynode).item<<endl;};
  57. }
  58.  
  59. int main(){
  60. List<int> l;
  61. cout<<l.size()<<endl;
  62. l.push_front(23);
  63. l.print();
  64.  
  65. return 0;}
  66.  
  67.  

the out put after compiling is

look push front gives23
here23
here -1077380900
0th entry is -1077380900

but this works fine if the for loop in print() is quoted.
what is the problem?
Aug 13 '07 #1
2 1274
ilikepython
844 Expert 512MB
While working on dynamic memory in c++ I noticed that values of my previous variables were changing whenever i invoke a loop.

for the following code::
Expand|Select|Wrap|Line Numbers
  1. template <class T>
  2. class List {
  3. private:
  4.         Node<T>* head;
  5.         Node<T>* tail;
  6.         int length;
  7. public:
  8.         List() {head = NULL;tail = NULL;length=0;};
  9.         int size();
  10.         bool empty();
  11.         void push_back(T);
  12.         void push_front(T);
  13.         void insert(int,T);
  14.         void print();
  15.         bool ismember(T);//pain
  16.  
  17.         // Member functions to
  18.         // interface with list
  19. };
  20.  
  21. template <class T>
  22. void List<T>::push_front(T a){
  23.     length++;                  //initially head->x1->null
  24.     Node<T>b(a,head);          //now head->new entry->x1->null
  25.     head = &b;
  26.     if(length == 1) tail = &b;
  27.     cout<<"look push front gives"<<(*head).item<<endl;
  28.     }
  29.  
  30. template <class T>
  31. void List<T>::print(){
  32.         cout<<"here"<<(*head).item<<endl;
  33.     Node<T> *mynode;
  34.     mynode = head;
  35.     cout<<"here   "<<(*head).item<<endl;
  36.     for(int i = 0;i < length;i++,mynode = (*mynode).next)
  37.     {cout<<i<<"th entry is "<<(*mynode).item<<endl;};
  38. }
  39.  

the out put after compiling is

look push front gives23
here23
here -1077380900
0th entry is -1077380900

but this works fine if the for loop in print() is quoted.
what is the problem?
I'm guessing that has something to do with undefined behaivior because otherwise I can't explain it. I couldn't believe it myself, the first time, but changing your push_front function seems to be working:
Expand|Select|Wrap|Line Numbers
  1. template <class T>
  2. void List<T>::push_front(T a){
  3.     length++;                  //initially head->x1->null
  4.     Node<T> b(a, head);        //now head->new entry->x1->null
  5.     head = &b;
  6.     if(length == 1) tail = &b;
  7.     cout<<"look push front gives"<<(*head).item<<endl;
  8.     }
You create the b node as an object and then assign it to a pointer. Try declaring it like this:
Expand|Select|Wrap|Line Numbers
  1. Node<T> *b = new Node<T> (a, head);
  2.  
And then assign to head like this:
Expand|Select|Wrap|Line Numbers
  1. head = b;
  2.  
Try it and see if it works.

PS In your node classs you have item and next declared as a public variable and you have accesor functions. That's pointless. Either make them private or you don't need setitem.
Aug 13 '07 #2
ilikepython
844 Expert 512MB
Also, I think the problem with assigning the pointer to an adress of an object is that that object is local so is deleted when the function exits. Then you have a pointer that points to garbage (nothing).
Aug 14 '07 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: meyousikmann | last post by:
I am having a little trouble with dynamic memory allocation. I am trying to read a text file and put the contents into a dynamic array. I know I can use vectors to make this easier, but it has to...
6
by: chris | last post by:
Hi all, I need to know, what is the difference between dynamic memory allocation, and stack allocation ? 1. If I have a class named DestinationAddress, when should I use dynamic memory...
6
by: Materialised | last post by:
Hi Everyone, I apologise if this is covered in the FAQ, I did look, but nothing actually stood out to me as being relative to my subject. I want to create a 2 dimensional array, a 'array of...
5
by: swarsa | last post by:
Hi All, I realize this is not a Palm OS development forum, however, even though my question is about a Palm C program I'm writing, I believe the topics are relevant here. This is because I...
3
by: Stephen Gennard | last post by:
Hello, I having a problem dynamically invoking a static method that takes a reference to a SByte*. If I do it directly it works just fine. Anyone any ideas why? I have include a example...
24
by: Ken | last post by:
In C programming, I want to know in what situations we should use static memory allocation instead of dynamic memory allocation. My understanding is that static memory allocation like using array...
1
by: Peterwkc | last post by:
Hello all expert, i have two program which make me desperate bu after i have noticed the forum, my future is become brightness back. By the way, my problem is like this i the first program was...
14
by: vivek | last post by:
i have some doubts on dynamic memory allocation and stacks and heaps where is the dynamic memory allocation used? in function calls there are some counters like "i" in the below function. Is...
20
by: sirsnorklingtayo | last post by:
hi guys please help about Linked List, I'm having trouble freeing the allocated memory of a single linked list node with a dynamic char* fields, it doesn't freed up if I use the FREE()...
10
by: swornavidhya.mahadevan | last post by:
Which allocation (Static / Dynamic) is suitable for the situation when we are trying to allocate for a overloaded memory when the memory is full and no space to allocate. What will happen if both...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.