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

Jennifer Davis davi0302 at algonquinc.on.ca
Tue Apr 8 17:08:40 EST 2003



Kathryn Hogg wrote:

> Uh oh, here you are deferencing the pointer that was passed but it's
> contents are undefined, so this is a likely place to core dump;

I think I have this all figured out now.  It seems I forgot to create a
new pStart object.  I am still having some difficulty with the deAlllocation
function and I have to write in a sort procedure as the .  I'm well on my
way.  I appreciate the nudge in the right direction by Kathryn, the advice
from Robert that I will retain for future work and the explanation by Jenny.
I really wish the instructor could have simplified it down to that level.

I will re-read about the stdio and stdlib libraries too.

Thanks...

Jenn




#include<iostream>   // for cin & cout
#include<stdio.h>    // for I don't know what
#include<stdlib.h>   // for I don't know what
#include<fstream>    // for file i/o

struct INVENTORY_NODE{
    INVENTORY_NODE *nextItem;
    char itemCode[7];
    int quantity;
    float price;
    }; // end struct INVENTORY_NODE

void createFile  (INVENTORY_NODE *pStart);
void createOutput(INVENTORY_NODE *pStart);
void deAllocate  (INVENTORY_NODE *pStart);

int main(){
    INVENTORY_NODE* pStart;
    pStart=new INVENTORY_NODE;

    createFile     (pStart);
    createOutput   (pStart);
    deAllocate     (pStart);
    }//end main

void createFile(INVENTORY_NODE *pStart){

    ifstream in;
    in.open("infile.txt");

    INVENTORY_NODE  temp;
    INVENTORY_NODE* p;
    INVENTORY_NODE* current;

    in >> temp.itemCode;

    current=NULL;
    p=pStart;

    while (!in.eof()){
        in >> temp.quantity;
        in >> temp.price;

        current=new INVENTORY_NODE;
        *current=temp;
        current->nextItem=NULL;

        p->nextItem=current;

        in >> temp.itemCode;
        } // end while

    in.close();
    }// end createFile

void createOutput(INVENTORY_NODE *pStart){
    ofstream out;
    out.open("outfile.txt");
    INVENTORY_NODE* current;
    current=pStart->nextItem;
    while(current!=NULL){
        out     << current->itemCode << "\t"
                << current->quantity << "\t"
                << current->price    << "\n";
        current=current->nextItem;
        } // end while
    out.close();
    } // end createOutput

void deAllocate(INVENTORY_NODE *pStart){
    INVENTORY_NODE* current;
    INVENTORY_NODE* temp;
    current=pStart;
    while (current !=NULL){
        temp->nextItem=current;
        delete current;
        current=temp;
        } // end while
    } // end deAllocate


More information about the Programming mailing list