Thread: Yet more Pointers and Linked List Questions

  1. #1
    Registered User (^Burt^)'s Avatar
    Join Date
    Sep 2013
    Posts
    26

    Yet more Pointers and Linked List Questions

    Hello All

    I have written tis program to read the words from a text file and simply count the number of occurrences each word has. I'm still trying to get to grips with the whole pointer and freeing up the memory afterwards principle.

    Could you please check out my listing a let me know if I have sucessfuly freed up all the malloc'd memory.

    Many thanks

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define NOTFOUND 0
    #define FOUND 1
    
    struct TheWord *AddNodeToList(char *);
    void showAllNode(struct TheWord *);
    struct TheWord *FindAWord(struct TheWord *, char *);
    void freeAllNode(struct TheWord *);
    
    struct TheWord
    {
        struct  TheWord *nextWord;
        char    theWord[100];
        int     theWordCounter;
    };
    
    int main(int args, char *argv[])
    {
        int readChar = 0;
        char thisWordBuffer[100]={'\0'};
        int thisWordCounter = 0;
        struct  TheWord *root = malloc(sizeof(*root));
        struct  TheWord *tail;
        struct  TheWord *incrementTheWord;
        /*SETUP AND OPEN THE FILE*/
        FILE *fp;
        /*THE FILE CAN BE ANY TEXT FILE FOR WHICH YOU WANT TO COUNT THE NUMBER OF OCCURANCES OF WORDS*/
        if((fp = fopen("I:\\C\\text.txt","r"))==NULL) {
            printf("Error:Can't open file");
            exit(-1);
        }
        /*CREATE THE ROOT NODE*/
        root->nextWord = NULL;
        strcpy(root->theWord,"root");
        root->theWordCounter = 0;
        tail = root;
        /*READ THE FILE UNTI EOF*/
        while((readChar = fgetc(fp))!=EOF) {
            /*IF THE CHAR READ IS NOT A PART OF A WORD I.E. A-Z*/
            if(readChar!=' ' && readChar!='\n' && readChar!='.' && readChar!=',') {
                thisWordBuffer[thisWordCounter] = readChar;
                thisWordCounter++;
            }
            else {
                /*ADD THE TERMINATOR*/
                thisWordBuffer[thisWordCounter]='\0';
                /*REINITIALISE THE COUNTER*/
                thisWordCounter = 0;
                /*IF THE WORD IS ALREADY IN THE LIST*/
                if((incrementTheWord = FindAWord(root,thisWordBuffer))!=NULL) {
                    /*INCREMENT THE COUNTER RATHER THAN ADD THE WORD AGAIN*/
                    incrementTheWord->theWordCounter++;
                }
                else {
                    /*IF THE WORD IS NOT IN LIST, ADD IT*/
                    tail->nextWord = AddNodeToList(thisWordBuffer);
                    /*KEEP THE TAIL MARKER UPTODATE*/
                    tail = tail->nextWord;
                }
            }
        }
        showAllNode(root);
        freeAllNode(root);
        free(root);
        return 0;
    }
    
    struct TheWord *AddNodeToList(char *wordToAdd)
    {
        /*CREATE A NEW STRUCURE AND GIVE IT SOME MEM*/
        struct TheWord *newNode = malloc(sizeof(*newNode));
        int x = 0;
        /*INITIALISE TO NULL AS THIS IS END NODE*/
        newNode->nextWord = NULL;
        /*ITERATE THROUGH THE WORD UNTIL '\0'*/
        while(*wordToAdd) {
            newNode->theWord[x] = *wordToAdd;
            x++;
            wordToAdd++;
        }
        /*ADD THE TERMINATOR - I'LL BE BACK!*/
        newNode->theWord[x]='\0';
        /*SET THE COUNTER TO ONE AS THIS SHOULD BE FIRST ADDITION TO THE LIST*/
        newNode->theWordCounter = 1;
        /*RETURN THE NODE*/
        return newNode;
    }
    
    void showAllNode(struct TheWord *rootNode)
    {
        /*ITERATE THROUGH ALL THE NODES FROM THE GIVEN ROOT*/
        while(rootNode = rootNode->nextWord) {
            printf("The Word [%20s] LISTED \t\t[%d] TIME(S)\n",rootNode->theWord, rootNode->theWordCounter);
        }
    }
    
    void freeAllNode(struct TheWord *rootNode)
    {
        struct TheWord *temp;
        temp = rootNode->nextWord;
        while(rootNode) {
            temp = rootNode->nextWord;
            free(rootNode);
            rootNode = NULL;
            rootNode = temp;
        }
    }
    
    struct TheWord *FindAWord(struct TheWord *rootNode, char *findWord)
    {
        int foundStatus = NOTFOUND;
        while((rootNode = rootNode->nextWord) && foundStatus == NOTFOUND) {
            if(strcmp(rootNode->theWord,findWord)==0)
            {
                foundStatus = FOUND;
            }
        }
        return rootNode;
    }

  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
    Code:
    $ valgrind --leak-check=full --show-reachable=yes ./a.out 
    ==2713== Memcheck, a memory error detector
    ==2713== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
    ==2713== Using Valgrind-3.6.1-Debian and LibVEX; rerun with -h for copyright info
    ==2713== Command: ./a.out
    ==2713== 
    <<<snip output>>>
    ==2713== Invalid free() / delete / delete[]
    ==2713==    at 0x4C282E0: free (vg_replace_malloc.c:366)
    ==2713==    by 0x4008E3: main (baz.c:67)
    ==2713==  Address 0x51d2040 is 0 bytes inside a block of size 112 free'd
    ==2713==    at 0x4C282E0: free (vg_replace_malloc.c:366)
    ==2713==    by 0x4009E9: freeAllNode (baz.c:106)
    ==2713==    by 0x4008D4: main (baz.c:66)
    ==2713== 
    ==2713== 
    ==2713== HEAP SUMMARY:
    ==2713==     in use at exit: 568 bytes in 1 blocks
    ==2713==   total heap usage: 214 allocs, 214 frees, 24,424 bytes allocated
    ==2713== 
    ==2713== 568 bytes in 1 blocks are still reachable in loss record 1 of 1
    ==2713==    at 0x4C28F9F: malloc (vg_replace_malloc.c:236)
    ==2713==    by 0x4E9A4CA: __fopen_internal (iofopen.c:76)
    ==2713==    by 0x40078B: main (baz.c:31)
    ==2713== 
    ==2713== LEAK SUMMARY:
    ==2713==    definitely lost: 0 bytes in 0 blocks
    ==2713==    indirectly lost: 0 bytes in 0 blocks
    ==2713==      possibly lost: 0 bytes in 0 blocks
    ==2713==    still reachable: 568 bytes in 1 blocks
    ==2713==         suppressed: 0 bytes in 0 blocks
    ==2713== 
    ==2713== For counts of detected and suppressed errors, rerun with: -v
    ==2713== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)
    1. The final free() is a duplicate.
    2. You don't call fclose()
    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 (^Burt^)'s Avatar
    Join Date
    Sep 2013
    Posts
    26
    Thank you. I'm going to have a look at the Valgrind. Do you have any suggestions regarding its use? Is there a tutorial site you can recommend for it? Can I only run it on my Ubuntu machine or is there a windows version hidden away somewhere?

    Cheers

  4. #4
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    valgrind for windows is in pre-alpha state Valgrind for Windows / Wiki / ProjectStatus

    There are some reasonable alternatives - but most that are working are not free, or rather costly - so you're better of with valgrind on your Ubuntu - free and reliable.
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointers Linked List
    By DecoratorFawn82 in forum C++ Programming
    Replies: 7
    Last Post: 06-08-2013, 03:02 PM
  2. Newbie questions about pointers and linked list
    By koplersky in forum C Programming
    Replies: 4
    Last Post: 10-07-2012, 08:43 PM
  3. Linked List with Two Pointers
    By aspekt9 in forum C Programming
    Replies: 5
    Last Post: 12-07-2009, 04:23 PM
  4. linked list and pointers : ??????
    By gemini_shooter in forum C Programming
    Replies: 7
    Last Post: 05-04-2005, 05:02 AM
  5. linked list questions...
    By revelation437 in forum C++ Programming
    Replies: 6
    Last Post: 04-22-2003, 04:42 PM