0

here is my code of a linked list with a header file however it works in debugger mode but in normal run time it crashes Please help!
Here's the header:

/* 

  Lab3 Abstract Data Type - header file

*/


/* Type Definitions */

typedef struct
{
   char  state[20];
   int   year_adopted;
   char *flower;
}STATE;

typedef struct nodeTag{
    STATE            state;
    struct nodeTag *link;
} NODE;

/*
 * The linked list header type
 */
typedef struct myListTag{
	int   count;
	NODE *pHead;
} MYLIST;


/* Prototype Declarations */
void	printMenu		(void);
char	*allocateString	(char *tempString);
int		getState		(char buffer[], STATE *pState);
void	getTargetState	(char targetState[]);
void	printState		(STATE *pState);
MYLIST	*buildList		(void);
MYLIST	*menuManager	(MYLIST *pList);
void	searchManager	(MYLIST *pList);
MYLIST	*insertManager	(MYLIST *pList);
MYLIST	*deleteManager	(MYLIST *pList);
int		searchList		(MYLIST *pList, NODE **pPre, NODE **pCur, char target[]);
MYLIST	*insertNode		(MYLIST *pList, NODE *pPre,  STATE *pState);
MYLIST	*deleteNode		(MYLIST *pList, NODE *pPre,  NODE *pCur);
void	printList		(MYLIST *pList);
MYLIST	*destroyList	(MYLIST *pList);

and here's the actual source code:

/**********************************************************************
** CIS   15C
** Summer, 2008
***************
**
** Lab 3: Singly-Linked List: Header Structure			      10 Points
**
**
***********************************************************************

  1. Read this program, try to understand what it does and how it works:
     DATA STRUCTURE DIAGRAMS, STRUCTURE CHART

  2. This program is giving a memory leak: try to figure out why, 
     and then solve the problem.

  3. Change this program by adding a header structure to the list;
     the header structure is to contain two fields:

        . pHead - pointer to the first data node in the list
		. count - stores the number of data nodes in the list.
  4. Also add another option: C - display the counter 
   
****************************************
**
**  Writen by: A. Student
**
**  Modified by: This is an incomplete version modified by the instructor.
**  If the student does not know where to start or is not sure he or she is heading
**  on the right direction. This version is highly recommended as the
**  starting point.
**  (1) This version has redesigned the linked list using a header data structure.
**  (2) Function prototypes have been modified to use the header.
**  (3) A new function has been added to create an empty linked list.
**      This function must be completed by the student.
**  (4) There are compilation warnings or errors to be removed by the student.
**  (5) The program will crash at run time because the createList function has
**      not been used. The key is to call this function to create an empty list.
**      The student should consider where this function should be used.
**  (6) Once the program runs, the student can then add the option C.
**  (7) The memory leak needs to be fixed.
**
**  Date: July 17, 2010
**
**********************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <crtdbg.h> 
#include "lab3.h"

#define FLUSH while (getchar () != '\n')
#define INPUT_STATES "states.txt"
/*
 * Creates an empty linked list.
 */
MYLIST *createList (void);

int main (void)
{
	MYLIST *pList;


	printf("\n\n\t\tLINKED LIST\n\n");
	printf("\tThis program builds and processes\n"
           "\ta sorted list of states.\n\n");

	pList = buildList();
	printf("Not");
	pList = menuManager(pList);
	pList = destroyList(pList);

    printf( _CrtDumpMemoryLeaks() ? "Memory Leak\n" : "No Leak\n");

	printf("\n\t\tThank you for using the program,"
		   "\n\t\tHave a great day!\n");


	return 0;

} /* main */

/* ========================== printMenu ===========================
	Prints the menu to the screen.
	   PRE  : nothing
	   POST : menu printed
*/
void printMenu (void)
{

	printf("\n\t\t*************************");
    printf("\n\t\t*                       *");
	printf("\n\t\t*   L - List            *");
	printf("\n\t\t*   S - Search          *");
	printf("\n\t\t*   I - Insert          *");
	printf("\n\t\t*   D - Delete          *");
	printf("\n\t\t*   M - Print Menu      *");
	printf("\n\t\t*   C - Display Counter *");
	printf("\n\t\t*   E - Exit            *");
	printf("\n\t\t*                       *");
	printf("\n\t\t*************************");

	return;

} /* printMenu */

/* ======================== allocateString ========================
    Uses a statically allocated string to create a 
    dynamically allocated string with the same contents.
    Pre:  tempString - statically allocated
    Post: string - dynamically allocated
*/
char *allocateString( char *tempString )
{
            
    char *string;
    int   stringSize;
    stringSize = strlen( tempString ) + 1;
    string = (char *) calloc (stringSize, sizeof (char));
   if ( string == NULL)
	{
        printf ("ERROR, not enough memory!!!\a\n"); 
		exit (103);
	}
    strcpy (string, tempString);
    return string;

}/* allocateString */  


/* ============================ getState ===========================
  This function reads the buffer and stores the information into a 
  state structure in the calling module. 
     PRE  : The buffer string containing the information for 
	        one state is passed to the function.
     POST : If valid, the state structure in the calling module is 
	        filled with data read from the string via pState and 
			TRUE is returned, otherwise False is returned.
*/
int  getState (char buffer[], STATE *pState)
{
    int   scanRes;
    char  tempName[201];
    scanRes = sscanf(buffer, "%[^\t]%4d\t%[^\n]",  pState->state, 
		                                        &pState->year_adopted,
                                                 tempName
                                         );
    if(scanRes != 3)
       printf("-*- Error reading state information! -*-\n");
    else
       pState->flower = allocateString( tempName ); 

	//free(pState->flower);
    return scanRes == 3;
} /* getState */


/* ======================== getTargetState =========================
	Gets a target state from the user.
	   PRE  : nothing
	   POST : number returned 
*/
void getTargetState (char targetState[])
{

	printf("\n\nPlease enter a state: ");
	fgets(targetState, 49, stdin);
	*(targetState + strlen(targetState) - 1 ) = '\0';
	                                       /* to eliminate '\n' */
	fflush(stdin);

	return;

} /* getTargetState */

/* ========================== printState ===========================
	Prints all fields in a STATE structure.
	   PRE  : pState
	   POST : state printed
*/
void  printState     (STATE *pState)
{
    printf("%4d %2s %s\n", pState->year_adopted, 
                           pState->state, 
                           pState->flower);
    return;

} /* printState */


/* ================================================================
   ======================= MANAGER FUNCTIONS ======================
   ================================================================ 
*/

/* =========================== buildList ==========================
	Build a sorted linked list.
	   PRE  : size - the size of the list
	   POST : linked list has been built
	   	      returns  pList - a pointer to the first node of the 
			  linked list
*/
MYLIST *buildList (void)
{

    STATE      state;
    FILE     *fpStates;
    MYLIST   *pList;
	NODE     *pPre ;
	NODE     *pCur ;
    char     *ioRes;
    char      buffer[200];


    if(!(fpStates = fopen(INPUT_STATES, "r")))
	{
       printf("-*- Could not open %s for reading! -*-\n", INPUT_STATES);
	   exit(100);
	}

	pList = createList();  /* empty list */
	while( (ioRes = fgets(buffer, 200, fpStates)) != NULL )
    {
        if( getState(buffer, &state) )
		{
			searchList (pList, &pPre, &pCur, state.state);
			pList = insertNode (pList, pPre, &state);
        }
	} /* while */
    
    if(fclose(fpStates) == EOF)
	{
       printf("-*- Error closing %s file! -*-\n", INPUT_STATES);
	   exit(111);
	}

	return pList;

} /* buildList */

/* ============================ menuManager =======================
	Process user's option by calling appropriate functions.
	   PRE  : pList - a pointer to the first node of a linked list
	   POST : pList - might be changed after inserting or deleting 
*/

MYLIST *menuManager (MYLIST *pList)
{
	char option;

	printMenu ();
	do
	{
        printf ("\n\nPlease enter an option (M - for Menu): ");
	    scanf  ("%c", &option);
        FLUSH;
	    option = toupper (option);
		
		switch(option)
		{
		    case 'L' : printList (pList);
				       break;
		    case 'S' : searchManager (pList);
				       break;
		    case 'I' : pList = insertManager (pList);
				       break;
		    case 'D' : pList = deleteManager (pList);
				       break;
		    case 'M' : printMenu ();
				       break;
		    case 'E' : printf("End of processing!\n");
                       break;
            default  : printf("*** Invalid option! ***\n");
		               printf("Enter one of the following letters: "
			                  "L, S, I, D, M, E: " );
					   break;
		} 
	} while (option != 'E');

	return pList;

} /* menuManager */


/* ======================== searchManager =========================
	Manages all functions related to search.
	    PRE  : pList - a pointer to the first node of a linked list
		POST : item searched and displayed on the monitor if found
*/
void searchManager (MYLIST *pList)
{
	int   found;
	char  targetState[51];
	NODE *pCur;
	NODE *pPre;


	getTargetState (targetState);
	found = searchList (pList, &pPre, &pCur, targetState);
	if (found)
    {
	    printf("Found: ");
        printState(&pCur->state);
    }
    else
		printf ("\n \"%s\" is not in the list\n", targetState);
	
    return;

} /* searchManager */

/* ======================== insertManager =========================
	Manages all functions related to insert.
	   PRE  : pList - a pointer to the first node of a linked list
	   POST : data inserted
              returns pList
*/
MYLIST *insertManager (MYLIST *pList)
{

	STATE     state;
    char     buffer[200];
	NODE    *pPre;
	NODE    *pCur;
	int      found;


    printf("Please enter information about a state in the following format:\n"
                "\n\t\tSTATE<tab>YEAR<tab>FLOWER\n\n" );
    fgets(buffer, sizeof(buffer), stdin);
	getState(buffer, &state);
	found = searchList (pList, &pPre, &pCur, state.state);
    if( found == 0 )
	{
	    pList = insertNode (pList, pPre, &state);
	    printf ("\n %s has been successfully inserted!\n", state.state);
	}
	else
		printf ("%s is already in the list\n", state.state);
		
    return pList;

} /* insertManager */

/* ======================== deleteManager =========================
	Manages all functions related to delete.
	   PRE  : pList the valid linked list.
	   POST : node deleted
              returns pList
*/
MYLIST *deleteManager (MYLIST *pList)
{

	char  targetState[51];
	NODE *pPre;
	NODE *pCur;
	int   found ;


	getTargetState(targetState);
	found = searchList (pList, &pPre, &pCur , targetState);
	if (found)
    {
        printf("%s - has been deleted\n", pCur->state.state);
        pList = deleteNode (pList, pPre, pCur);
    }
	else
		printf(" %s is not in the list.\n\n", targetState);

	return pList;

} /* deleteManager */

/* ================================================================
   ================ BASIC LINKED LIST FUNCTIONS ===================
   ================================================================ 
*/

/* ========================== searchList ==========================
	Given key value, finds the location of a node.
	   PRE  : pList - a pointer to the first node of a linked list
	   	      pPre points to variable to receive predecessor
		      pCur points variable to receive current node
		      target is key being searched
	   POST : pCur points to first node with equal/greater key 
                   -or- null if target > key of last node
		      pPre points to largest node smaller than key 
                   -or- null if target > key of first node
		      function returns 1 if found, 0 if not found
*/
int searchList (MYLIST *pList, NODE **pPre, NODE	**pCur, char target[])
{

	int found = 0;


	*pPre = NULL;
	*pCur = (NODE*)pList;
	while(*pCur != NULL && strcmp(target, (*pCur)->state.state) > 0){
		*pPre = *pCur;
		*pCur = (*pCur)->link;
	} /* while */

	if(*pCur != NULL && strcmp(target, (*pCur)->state.state) == 0)
		found = 1;
	return found;

} /* searchList */

/* ========================== insertNode ==========================
	Inserts a node into a linked list.
       PRE  : pList - a pointer to the first node of the linked list
	                  it may be NULL
	   	      pPre points to new node's logical predecessor
		      item contains data to be inserted
	   POST : returns pList
*/
MYLIST *insertNode (MYLIST *pList, NODE *pPre, STATE *pState)
{

	NODE *pNew;

	
	if(!(pNew = (NODE *)malloc(sizeof(NODE))))
	{
		printf("Memory overflow in inser\n");
		exit(100);
	}

	pNew->state = *pState;
	if(pPre == NULL)
    {
		pNew->link = (NODE*)pList;
		(NODE*)pList	   = pNew;
	} 
	else 
    {

		pNew->link = pPre->link;
		pPre->link = pNew;
	} 

	return pList;

} /* insertNode */

/* ========================== deleteNode ==========================
	Deletes a node from a linked list.
	   PRE  : pList - a pointer to the first node of a linked list
	  	      pPre points to node before the delete node
	 	      pCur points to the node to be deleted
	   POST : deletes and recycles pCur
		      returns pList
*/
MYLIST *deleteNode (MYLIST *pList, NODE *pPre, NODE *pCur)
{


	if(pPre == NULL)
		(NODE*)pList = pCur->link;
	else
		pPre->link = pCur->link;

	free (pCur);

	return pList;

} /* deleteNode */

/* =========================== printList ==========================
	Prints a linked list.
	   PRE  : pList - a pointer to the first node of a linked list
	   POST : List has been printed.
*/
void printList (MYLIST *pList)
{

	NODE *pWalker;

	pWalker = (NODE*)pList;
	printf("\n\n");
	while(pWalker)
	{
		printState(&pWalker->state);
        pWalker = pWalker->link;
	} 
	printf("\n");

    return;

} /* printList */

/* ========================= destroyList ==========================
	Free the memory after being used by linked list.
	   PRE  : pList - a pointer to the first node of a linked list
	   POST : linked list destroyed; returns NULL
*/
MYLIST *destroyList (MYLIST *pList)
{

	NODE *pDel;
	NODE *pPre;


	pDel = (NODE*)pList;

	while(pDel != NULL)
	{
		pPre = pDel;
		pDel = pDel->link;
        free (pPre); 
	} 

	return NULL;

} /* destroyList */

/* ========================= createList ==========================
	Create an empty linked list. 
	   PRE  : none
	   POST : a pointer to an empty MYLIST is returned.
*/
MYLIST *createList(void)
{
	/* To be completed */
	MYLIST *pList = NULL; /* change this to allocate memory for MYLIST */
	/* add code here to initialize MYLIST */
	
	pList = (MYLIST*) malloc (sizeof(MYLIST));
	if (pList){
		pList->pHead = NULL;
		pList->count = 0;
	}

	return pList;
}
1
Contributor
1
Reply
3
Views
6 Years
Discussion Span
Last Post by d34dw4rd
0

my thoughts are that it is the insert node is placing stuff in the first node when it shouldn't becuase it is the MYLIST and thus causing problems throughout... but I don't know how to implement the change if that is the case

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.