OK - I got home and cranked your code through valgrind. Essentially, valgrind thinks you have corruption at list.cpp:180 where you delete pTemp. As usual, it wasn't perfect, but it was great for narrowing down the vicinity of the problem; it also caught the problem earlier than we would expect: during the
first run. I looked at your implementation carefully and the delete looks right on Line 180. However, the point of corruption gave me a clue. It was during the first run, when you were trying to delete "See" at the head of your list.
I eyeballed your code some more and replace list.cpp:154
pTemp = head;
with
head = pTemp->next; // since we are going to delete the head node, make sure we repoint head
Reran valgrind to verify and it all worked.
So it was memory corruption after all. I would recommend that you download and install valgrind - with this tool, I was able to debug this code in about 10 minutes:
http://valgrind.org/
This kind of spookiness is typical of memory corruption. When strange program behavior starts to make you believe in voodoo, it's a good idea to pull out some memory-checking tools to get your sanity back.
GL.
BTW, +1 Disch:
unless the head is being deleted somewhere, you're right, that makes no sense at all. |
Damn! He's good! Listen to all his recommendations.
For your benefit, this is a snippet of what a valgrind run with output looks like:
/tmp/Project4/$ valgrind ./p04 p04input3.txt
==11379== Memcheck, a memory error detector
==11379== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==11379== Using Valgrind-3.6.0.SVN and LibVEX; rerun with -h for copyright info
==11379== Command: ./p04 p04input3.txt
==11379==
## p04input3.txt -- Test List(), ~List(), Delete()
# Test successful delete
List() -- Successful
Print() -- Head { }
Append(See) -- successful
Print() -- Head { See }
Append(Spot) -- successful
Print() -- Head { See Spot }
Append(run) -- successful
Print() -- Head { See Spot run }
Append(swiftly) -- successful
Print() -- Head { See Spot run swiftly }
Append(away) -- successful
Print() -- Head { See Spot run swiftly away }
Delete(run) -- successful
Print() -- Head { See Spot swiftly away }
Delete(Spot) -- successful
Print() -- Head { See swiftly away }
Delete(See) -- successful
==11379== Invalid read of size 8
==11379== at 0x4ECAB20: std::basic_ostream<char, std::char_traits<char> >& std::operator<<
<char, std::char_traits<char>, std::allocator<char> >(std::basic_ostream<char,
std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> >
const&) (in /usr/lib/libstdc++.so.6.0.13)
==11379== by 0x4028A6: List::Print() const (list.h:89)
==11379== by 0x402347: main (main.cpp:116)
==11379== Address 0x5962440 is 0 bytes inside a block of size 16 free'd
==11379== at 0x4C27EFF: operator delete(void*) (vg_replace_malloc.c:387)
==11379== by 0x401A65: List::Delete(std::string) (list.cpp:180)
==11379== by 0x402142: main (main.cpp:90)
|