Re: [Dev-C++] Single Linked List Problem
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Luigi S. <gi...@li...> - 2003-06-07 04:24:12
|
Hi Andre',
IMHO, code below should be changed such that:
- use of function "gets" is avoided (because it does not check
if overflow occurs)
- memory used for the nodes of the list should be deallocated
- initialization of pointers START and LAST, before placing
any element on the list, does not require them pointing to some
allocated memory
- if portable code is of interest, use of OS specific functions
(such as Dos "PAUSE") should be avoided
Item #1 is a warning that Gcc issues (if you enable warnings)
Item #2 is the reason of your mail, I'll say something about it later
Item #3 is a small detail you probably overlooked, see comments in code below
Item #4 reflects my personal tastes
Now back to your original question. Generally, a container (like a list)
has functions that push elements (as the slstore you provide) as well as
function that pop elements. Also there might be the need for a clean-up
function, which would remove all items on the list when you no longer
need the container (and haven't popped out all elements yet). In this case,
you are concerned with cleaning up operations, a possible inteface to such
a function, could be:
void
clean_up(struct address **start, struct address **last);
A simple implementation could be:
- while there is something on the list (that is, *START is not 0)
- duplicate value of *START using a temporary pointer
- update *START (so that it points to second element, which
eventually may be 0, when there is only one element left on the list)
- free memory pointed by the temporary pointer
- update *LAST, setting it to 0, thus leaving the list in a
consistent state
I hope the above was of some help.
--
>> gisan >>
On Thu, Jun 05, 2003 at 10:58:18PM -0300, Andr? Mac?rio Barros wrote:
> Dear Users,
>
> I need to discover a way to use the "free" command to correctly avoid 5
> records dinamically allocated in a simple Single Linked List program.
> Here are some pieces of it:
>
> [...]
>
> int main()
> {
>
> struct address *info, *start, *last;
>
> init(&start); /* here start is assigned some memory */
> start=NULL; /* throwing away the address, so can't free it anymore */
> init(&last); /* allocating memory for last */
> last=NULL; /* throwing away the address */
/* above 4 lines could be folded into one line,
also avoiding the memory leaks related to them:
start = last = 0;
*/
> for(i=0; i<MAX; i++)
> {
> init(&info);
> printf("Enter name: ");
> gets(info->name); /* should be avoided */
> printf("Enter phone: ");
> gets(info->phone); /* should be avoided */
> slstore(info, &start, &last);
> }
> ...
> system("PAUSE"); /* this makes your code non portable, also
it is not needed, if you run console
application from a console window */
> return(0);
> }
>
> [...]
|