Thread: Linked List Reference Pointer problems

  1. #1
    Registered User
    Join Date
    Nov 2007
    Location
    Singapore
    Posts
    24

    Linked List Reference Pointer problems

    Hi All

    I am loading a linked list from file pushing to the list from a reference pointer

    However when i load the file for 2nd time (for debugging purpose to see if it rejects duplicates) one of my data got corrupted

    The first time i load the file it loads perfectly fine

    The 2nd time i load the employee code became -842150451, and the entire validation failed can anyone guide me on how to solve this problem?


    Code:
    int loadEntryForText(char *str , struct EmployeeData ** emp)
    {
    	int n, exist, code;
    	int count = 0;
    	char field[30];
    	
    	struct EmployeeData* currentEmp = *emp;
    	
    
    	struct EmployeeData* newEmp = NULL;
    	struct Pay* newData = NULL;
    	struct Date* dob = NULL;
    
    	newEmp = malloc(sizeof(struct EmployeeData));
    	newData = malloc(sizeof(struct Pay));
    	dob = malloc(sizeof(struct Date));
    
    	//Start string parsing
    	while (sscanf(str, "%29[^|]%n", field, &n) == 1 ){
    		//printf("field = \"%s\"\n", field);
    
    		switch (count){
    			case 0:
    				code = atoi(field);
    				
    				for (currentEmp=*emp; currentEmp!=NULL; currentEmp=currentEmp->nextElement){ 
    					if (code == currentEmp->code){ //Check if employee code exists
    						printf("\n\tThe employee code: %d you have entered already exist, \n\tand thus this entry will not be added.\n\n\t", code);
    						exist = TRUE;
    						pause();			
    					}
    					else{
    						exist = FALSE;
    						newEmp->code = code;
    					}	
    				}
    				//printf("%d\n", newEmp->code);
    				break;
    			case 1:
    				newEmp->name = (char*)malloc((strlen(field)+1)*sizeof(char));
    				strcpy(newEmp->name, field);
    				//printf("%s\n", newEmp->name);
    				break;
    
    			case 2:
    				newEmp->age = atoi(field);
    				//printf("%d\n", newEmp->age);
    				break;
    			
    			case 3:
    				dob->day = atoi(field);
    				//printf("%d\n", dob->day);
    				break;
    			
    			case 4:
    				dob->month = atoi(field);
    				//printf("%d\n", dob->month);
    				break;
    
    			case 5:
    				dob->year = atoi(field);
    				//printf("%d\n", dob->year);
    				break;
    			
    			case 6:
    				newEmp->jobCat = field[0];
    				//printf("%c\n", newEmp->jobCat);
    				break;
    
    			case 7:
    				newEmp->basicPay = atof(field);
    				//printf("%lf\n", newEmp->basicPay);
    				break;
    			
    			case 8:
    				newEmp->hours = atoi(field);
    				//printf("%d\n", newEmp->hours);
    				break;
    
    			case 9:
    				newData->otHours = atoi(field);
    				//printf("%d\n", newData->otHours);
    				break;
    
    			case 10:
    				newData->otPay = atof(field);
    				//printf("%lf\n", newData->otPay);
    				break;
    
    			case 11:
    				newData->weeklyPay = atof(field);
    				//printf("%lf\n", newData->weeklyPay);
    				break;
    				
    		}
    		count++;
    		str += n; /* advance the pointer by the number of characters read */
    		if ( *str != '|' )
    		{
    			newEmp->dataElement = newData;
    			newEmp->dob = dob;
    			newEmp->nextElement = *emp;
    			*emp = newEmp;
    			
    			break; // didn't find an expected delimiter
    		}
    		++str; /* skip the delimiter */
    	}
    
    	return 1;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    -842150451 == 0xCDCDCDCD
    With that in mind, read this.
    http://www.codeguru.com/Cpp/W-P/win3...cle.php/c9535/
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Nov 2007
    Location
    Singapore
    Posts
    24
    Hi, i understand that there is a memory leak in my application but i cannot find out where is the leak... can anyone help me??

  4. #4
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    You're not giving enough information to tell you exactly where your mistake is but fact is:
    Code:
    for (currentEmp=*emp; currentEmp!=NULL; currentEmp=currentEmp->nextElement){
    Here you check for currentEmp!=NULL that means that you expect an element where nextElement is set to NULL.
    I can't see anywhere that you set nextElement to NULL.
    On the other hand
    Code:
    			newEmp->nextElement = *emp;
    Makes me think that this is supposed to be a circular linked list.
    Kurt

  5. #5
    Registered User
    Join Date
    Nov 2007
    Location
    Singapore
    Posts
    24
    This are my structures

    Code:
    struct EmployeeData
    {	
    	int		code;		/* Employee Code */
    	char *	name;		/* Employee Name */
    	int		age;		/* Employee Age	 */ 
    	double	basicPay;	/* Basic pay of Employee */
    	char	jobCat;		/* Job Category in char of Employee */
    	int		hours;		/* Hour works by Employee */
    
    	struct	Date *			dob;			/* Date of birth data element */
    	struct	Pay *			dataElement;	/* Employee Pay data element */
    	struct	EmployeeData *	nextElement;	/* Linked List, next element */
    };
    
    /*
    Structure for Pay data
    */
    struct Pay{
    
    	int		otHours;	/* Overtime hours */
    	double	weeklyPay;	/* Weekly pay */
    	double	otPay;		/* Overtime pay */
    };
    
    /*
    Structure for Date
    */
    struct Date{
    	int  month;	/* Month of year */
    	int  day;	/* Day of month */
    	int  year;	/* year */
    };
    This is what my lecturer taught me to do.. to push using a reference pointer
    Code:
    	//PUSH
    	newEmp->nextElement = *user;
    	*user = newEmp;
    I have another problem that is whenever i try to delete an element

    Code:
    void removeElement(int n, struct EmployeeData* list)
    {
    	struct EmployeeData *previous = list;
    	
    	while(previous != NULL)
    	{
    		if(previous->code == n)
    		{
    			free(previous);
    			printf("\n\n\tEmployee %d successfully deleted\n\t", n);
    			break;
    			return;
    		}
    		else
    		{
    			previous = previous->nextElement;
    		}
    	}
    
    	if(previous == NULL )
    	{
    		printf("\n\tThe employee code you have entered does not exist.\n\n\t");
    
    	}
    }
    After i delete the element when i display a counter
    Code:
    int listLength(struct EmployeeData* head) {
    
    	struct EmployeeData* current = head;
    	int count = 0;
    
    	while (current != NULL) {
    		count += 1;
    		current = current->nextElement; //Error Reading an element, I have already freed the pointer but i get a error reading exception here
    	}
    
    	return count;
    }

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    When you remove the element, you will need to also modify the pointers for the next and/or prev pointer so that the deleted item is properly removed from the list. Fortunately (?) Microsofts runtime library fills in deleted objects with "garbage" so you detect it immediately you try to access the element, rather than later on.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  7. #7
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Yes, they do. Only in debug, however. So I'd definetly call it a "fortunately"
    Last edited by Elysia; 12-17-2007 at 06:16 AM.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  8. #8
    Registered User
    Join Date
    Nov 2007
    Location
    Singapore
    Posts
    24
    Hi, how do u deal with those.. i tried alot of things but it just give me the same exception

  9. #9
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Well, when you delete an element on a linked list, you need to "jump" the next of the element pointing to the deleted item, to the next one after the deleted one. This usually means tracking the element BEFORE the one you've found in some way or another.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  10. #10
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Code:
    typedef struct EmployeeData EmployeeData;
    void DeleteElement(EmployeeData ** pHead, EmployeeData* pToDelete)
    {
    	EmployeeData* pCurrent;
    	if (pToDelete == *pHead)
    	{
    		/* If we're deleting the first node in the list, aka the head */
    		*pHead = (**pHead).nextElement;
    		free(*pHead);
    		return;
    	}
    	/* Find previous node */
    	for (pCurrent = *pHead; pCurrent->nextElement != pToDelete && pCurrent->nextElement != NULL; pCurrent = pCurrent->nextElement);
    	/* Set next node to the node after the node we delete. Also make sure we don't try to walk to a node that does not exist.
    	Check if there's a next node beyond the current */
    	pCurrent->nextElement = pCurrent->nextElement != NULL ? pCurrent->nextElement->nextElement : NULL;
    	free(pToDelete);
    }
    A typical example on how to free a node in a (single) linked list, to add to matsp's explanation.
    Code is only pseudo.
    Last edited by Elysia; 12-17-2007 at 07:47 AM.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  11. #11
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    And of course, there is a special case when the first element is being deleted. I've seen someone use some double-pointer magic to point to "head" and then follow the next pointers.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  12. #12
    Registered User
    Join Date
    Nov 2007
    Location
    Singapore
    Posts
    24
    Hi, i could delete now but not the 1st element as pointed out by u guys can anyone tell me guide me??

    Code:
    void removeElement(int n, struct EmployeeData ** list)
    {
    	struct EmployeeData *previous = *list;
    	struct EmployeeData *current = previous->nextElement;
    	
    	while(previous != NULL)
    	{
    		if (previous->code == n)
    		{
    			
    			free(previous); //I am confused, the 1st element wouldnt delete for previous 
    			printf("\n\n\tEmployee %d successfully deleted\n\t", n);
    			break;	
    		}
    
    		else if(current->code == n)
    		{
    			previous->nextElement = current->nextElement;
    			free(current);
    			printf("\n\n\tEmployee %d successfully deleted\n\t", n);
    			break;		
    		}
    		else
    		{
    			previous = current;
    			current = current->nextElement;
    		}
    	}
    
    	if(current == NULL )
    	{
    		printf("\n\tThe employee code you have entered does not exist.\n\n\t");
    
    	}
    }

  13. #13
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I'm confused by that code. What is list pointing to? And what is n? Are you trying to delete a node whose valu (or data) is == n? If yes, then that's now how a delete node function works. The delete funciton will only delete the node and fix the list. The caller should find the node you want to delete. Make another function of that if you wish.
    To delete the first node is a list, simply update the head - or the pointer that points to the first node.

    I updated the pseudo code; have a look again. Maybe you'll learn something.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  14. #14
    Registered User
    Join Date
    Nov 2007
    Location
    Singapore
    Posts
    24
    Hi, i tried alot of things based on ur pseudo and its not working.. can you point me to a tutorial or something with some sample codes? its getting frustating

  15. #15
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    There are tutorials on linked lists on this site, www.cprogramming.com/tutorial


    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 06:54 PM
  2. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  3. circular doubly linked list help
    By gunnerz in forum C++ Programming
    Replies: 5
    Last Post: 04-28-2007, 08:38 PM
  4. singly linked to doubly linked
    By jsbeckton in forum C Programming
    Replies: 10
    Last Post: 11-06-2005, 07:47 PM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM