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.
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 = newvoid;
delete popElement; you can't delete pointer to stack
when defined like: Element *popElement = new Element now you can delete.
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/
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>