[prog] C++ - linked list and segmentation fault

Jimen Ching jching at flex.com
Tue Apr 8 11:25:50 EST 2003


On Tue, 8 Apr 2003, Jennifer Davis wrote:
>#include<iostream.h> // for cin & cout
>#include<stdio.h>    // for I don't know what

As Robert mentioned, the .h is deprecated.  But he didn't mention that
stdio.h is also deprecated.  If you need reference to the C standard
library, use cstdio and friends.  Basically, just remove the .h and
prepend a 'c' to the filename.

As for why anyone might want to use the C standard library; someone might
want to use things like sprintf.  Though the C++ standard library provides
similar facilities.  Its just that most people don't know about them.
There's also no equivalent of the memcpy and friends.  So cstdio and
cstdlib are the most often used ANSI C headers.  Note, this header
filename style only applies to ANSI C headers.  POSIX headers do not have
any equivalent style.  So those still use .h extensions.

As for your linked list problem, The other suggestions are fine for new
programmers.  But one thing I always see people overlook is the use of a
good debugger.  There are occasions where printf or cout are necessary.
But a very large number of defects can easily be found with a debugger.
I've experienced where co-workers would spend hours tracking down bugs
with random placements of cout.  Then they ask for my help and I ask them
to run it through a debugger.  We found the problem within half an hour.

There are many graphical frontends to gdb and other debuggers.  So if a
command line interface scares you, try some of the more powerful GUI's.
DDD is one such frontend.  Matter of fact, DDD allows you to display data
structures in a graphical way.  Perfect for the type of bug you are
running into here.

As for your difficulty with C pointers.  You're not alone.  A lot of
people find it hard to learn.  This is probably why there are so many
defects related to memory.  When I first learned about pointers, the
professor used an analogy which seems to be very helpful.  He compared
pointers to a card catalog of a library.  I'm not sure if other countries
have such things.  Basically, a card catalog is a collection of index
cards which contain information about books.  The most important
information on these cards is the location of the actual book, i.e. the
Dewey Decimal System identifier or some other system identifier value.

You can think of pointers this way:

	Book book; // A book.
	Book *index_card; // An index card.
	index_card = &book;

Basically, a pointer tells you where you can find the actual object in
memory.  Now, extend this concept to a linked list.  I can't think of an
analogy for a linked list, but you get the idea.  :)

--jc
-- 
Jimen Ching (WH6BRR)      jching at flex.com     wh6brr at uhm.ampr.org


More information about the Programming mailing list