S
sam
I am using Sun server which did not have STL. I wrote a small Stack class as
I listed below. If I remove one item from stack and want to free that
memory area. I am using "data" member (temp variable) to hold and return
and deleting original one.
My question is:
How I free memory and return value from that memory area? ( scroll down to
function pop) I did not want to use line 39.
Please comment also over all program. Thank you very much in advance.
#include<iostream>
#include<string>
#include<stdlib>
class Stackitem{
public:
char *item;
Stackitem *next;
};
class Stack{
private:
Stackitem* top;
char* data; // Temp member
public:
Stack();
void push( char *);
char* pop();
};
Stack::Stack() {
data = new char[40];
}
void Stack:ush(char* val1){
Stackitem *st = new Stackitem;
st->item = new char[strlen(val1)+1];
st->item=val1;
top->next=top;
top=st;
}
char* Stack:op(){
Stackitem* t =top;
top = top->next;
strcpy(data,t->item); // Line 39 (I did not want to
use this line. what is the alternative)
delete t;
return t->item;
}
int main(){
Stack *s1 = new Stack();
s1->push("20");
s1->push("30");
s1->push("50");
cout << "pop="<<s1->pop() <<"\n" ;
Stack s2;
s2.push("500");
cout << "pop="<<s2.pop() <<"\n" ;
delete s1;
return (0);
}
I listed below. If I remove one item from stack and want to free that
memory area. I am using "data" member (temp variable) to hold and return
and deleting original one.
My question is:
How I free memory and return value from that memory area? ( scroll down to
function pop) I did not want to use line 39.
Please comment also over all program. Thank you very much in advance.
#include<iostream>
#include<string>
#include<stdlib>
class Stackitem{
public:
char *item;
Stackitem *next;
};
class Stack{
private:
Stackitem* top;
char* data; // Temp member
public:
Stack();
void push( char *);
char* pop();
};
Stack::Stack() {
data = new char[40];
}
void Stack:ush(char* val1){
Stackitem *st = new Stackitem;
st->item = new char[strlen(val1)+1];
st->item=val1;
top->next=top;
top=st;
}
char* Stack:op(){
Stackitem* t =top;
top = top->next;
strcpy(data,t->item); // Line 39 (I did not want to
use this line. what is the alternative)
delete t;
return t->item;
}
int main(){
Stack *s1 = new Stack();
s1->push("20");
s1->push("30");
s1->push("50");
cout << "pop="<<s1->pop() <<"\n" ;
Stack s2;
s2.push("500");
cout << "pop="<<s2.pop() <<"\n" ;
delete s1;
return (0);
}