Does this code has problems?

J

Jianwei Sun

Hello, all,

I am reading some code from an interview book.


It has a stack pop function implementation like this..

typedef struct Element {
struct Element *next;
void *data;
} Element;



bool pop( Element **stack, void **data ){
Element *elem;
if (!(elem = *stack)) return false;

*data = elem->data;
*stack = elem->next;
delete elem;
return true;
}

my question is this, since you already delete the element in the pop function,
the data returned will be invalid, since it's part of the element.

Can anybody points out whether I have some misunderstanding here?

Thanks,
J.W.
 
R

Rajib

Jianwei said:
Hello, all,

I am reading some code from an interview book.


It has a stack pop function implementation like this..

typedef struct Element {
struct Element *next;
void *data;
} Element;



bool pop( Element **stack, void **data ){
Element *elem;
if (!(elem = *stack)) return false;

*data = elem->data;
*stack = elem->next;
delete elem;
return true;
}

my question is this, since you already delete the element in the pop
function,
the data returned will be invalid, since it's part of the element.

Can anybody points out whether I have some misunderstanding here?

Thanks,
J.W.
pop doesn't delete data, it just elem, which just points to data.
 
J

J.W.

----- Original Message -----
From: "Alf P. Steinbach" <[email protected]>
Newsgroups: comp.lang.c++
Sent: Tuesday, July 15, 2008 11:13 PM
Subject: Re: Does this code has problems?

* Jianwei Sun:

What's that?



Except if this is code that's wrapped by a template class, and except if
this is code that's meant to illustrate Really Bad Coding, you should
throw that book on the flames (after appropriately informing this group
about which book it is).

First, void* is an abomination, except for the mentioned wrapping by a
template.

Second, the 'typedef' is C style, completely unnecessary in C++.

[ This is a pretty decent book, and it's my fault that I didn't mention the
original code is C style, not c++ style].

In C++ those arguments should be references.



No, the data is not part of the element: the element just contains a
pointer to the data.

[Thanks, this helps me a lot. Further question, as you said, the data is not
part of the elment, so
in the destructor, I need delete both the data and element since the element
just contains a pointer to the data. ]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top