pointers stack

assuming stack interface: where data is a pointer to some value and next is the next pointer.

1
2
3
4
5
6
7
8
9
10
11
12
13
void *Stack::pop() {
    Element *popElement = head;
    void *mydata;

    /* Assume StackError exception class is defined elsewhere */
    if( head == NULL )
        throw StackError( E_EMPTY );

    mydata = head->data;//will this be a problem
    head = head->next;
    delete popElement;
    return mydata;
}


1. Since myData is a pointer created locally would my return myData go out of scope.

2. Since i delete the node where head is and myData points to that isn't that a problem since that memory is lost.

Tell me on the issues of this code. Thanks
mydata will go out of scope cos it's staticaly alocated and return address will point to strange value .. so you shoult create it dynamicaly
void* myData = new void;

delete popElement; you can't delete pointer to stack
when defined like: Element *popElement = new Element now you can delete.

closed account (3hM2Nwbp)
Templates are often a better alternative than void pointers, just thought I'd mention that. The standard template library also has a stack implementation if you want to check that out. http://cplusplus.com/reference/stl/stack/
@sasanet:

1) It would be fine, because you are only losing the address (mydata), which you are returning, not the pointed to data.

2) No, because just contains a pointer to the data. If the data was dynamically allocated, then you would have to delete it later however.
Last edited on
Templates don't allow a stack of non-homogenous types.
@firedraco

Since there is a call on delete popElement; and mydata = head->data; points to a segment that is deleted(head->data is a node that is deleted ), technically this is a case of undefined behavior.


assuming if data has been declared as int data; and not a pointer; then what happens, assuming the casting is done on the void pointer. So now it will point to garbage right>

Last edited on
@firedraco
1) It would be fine, because you are only losing the address (mydata), which you are returning, not the pointed to data.

heh you're wright zzzz learning :)
No, head->data is a pointer, so the actual data is still there.
crystal clear...thanks...just needed feedback...
Topic archived. No new replies allowed.