Thread: i dont understand what i did wrong-allocate and Memory

  1. #1
    Registered User
    Join Date
    Nov 2019
    Posts
    12

    i dont understand what i did wrong-allocate and Memory

    i did some files - makefile , functions(down), main(down) and h-declaration file and when i want to enter some input from file like "once upon a time" and this build me char char like a tree and print how much words i have . and i get always error
    Segmentation fault (core dumped)
    help?

    all node build like that

    Code:
    typedef struct node {
    
        char letter;
        long unsigned int count;
        struct node* children[NUM_LETTERS];
    
    
    } node;







    Code:
    #include <stdio.h>
    #include <string.h>
    #include "treeFunctions.h"
    #include <stdlib.h>
    
    
    
    
    
    
    
    
    
    
    int main(int argc, char* argv[]) {
    
    
        char* r = "r";
        node* head = newNode();
        buildTree(head);
    int biggestWordLength=bigWordLength(head, 0);
    char* word = (char*)malloc(biggestWordLength);
    
    
        if( (strcmp(argv[1],r)==0) && (argc==2) )
    {
    printWordReverse(head,word,0);}
    
    
        else {
            printWord(head,word,0);
        }
    
    
    
    
    free(word);
        freeLevelsOnTree(head);
    
    
    
    
        return 0;
    }



    ////


    Code:
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    #include "treeFunctions.h"
    #include <stdlib.h>
    
    
    
    
    node* newNode() {
    
    
    node* n=NULL;
        n= (node*)malloc(sizeof(node));
        if (n==NULL){
    printf("error-malloc not allocate memory");
    return NULL; }
        n->count = 0;
    int i;
        for (i = 0; i < NUM_LETTERS; i++){
            n->children[i] = NULL;}
    
    
        return n;    
    }
    
    
    
    
    
    
    void buildTree(node* head)
    {
    char character;
    node* pointNode = head;
    
    do{
    
    
    character = getchar();
    character = tolower(character); //Turns a big letter into a small letter lib <ctype.h>
    
    if(character == EOF)
    {
    pointNode->count++;
    return;
    }
    
    
    // if(!( character>='a' && character<='z') )
    // {continue;}
    
    
    
    
    if (!isCharLeagal(character)) continue;
    
    
    
    if (character=='\n' || character==' ' || character=='\t')
    {
    
    if ( (pointNode!=NULL) && (pointNode != head) )
    {
    pointNode->count++;
    pointNode= NULL;
    }
    
    continue;
    }
    
    
    
    
    if(pointNode ==NULL){
    pointNode = head;} 
    
    pointNode = addword(head, pointNode, character);
    
    
    
    
    
    }while(character!=EOF);
    
    
    
    
    
    
    }
    
    
    
    
    
    
    
    
    node* addword(node* head,node* pointNode,char character){
    
    
    int i = (((int)character)-((int)'a')) ; //calculate the place of the index
    
    
    if( (pointNode->children[i])==NULL ){
    pointNode->children[i] = newNode();
    pointNode->children[i]->letter = character; 
    }
    
    
    pointNode = pointNode->children[i]; 
    
    
    return pointNode;
    
    
    }
    
    
    
    
    
    
    void freeLevelsOnTree(node* head)
    {
    
    node* nPointer = head;
    
    for (size_t i=0; i<NUM_LETTERS;i++)
    {
    if(nPointer->children[i] !=NULL){
    freeLevelsOnTree(nPointer->children[i]);
    }
    }
    
    
    free(nPointer);
    
    
    
    
    }
    
    
    
    
    
    
    int bigWordLength(node* n, int counter){
    
    
    int i;
    int length = counter;
    
    
    for(i = 0; i < NUM_LETTERS; i++)
    {
    if(n->children[i]!=NULL)
    {
    int length2 = bigWordLength(n->children[i], counter + 1);
    
    
    if(length2 > length)
    {
    length = length2;
    }
    
    
    }
    }
    
    
    
    
    return length;
    }
    
    
    
    
    
    
    
    
    void printWord(node* head,char strWord[], int levelTree){
    
    
    node* nPointer = head;
    
    
    if (nPointer == NULL){
    return;}
    
    
    if (nPointer->count > 0){
    strWord[levelTree] = '\0';
    printf("%s\t %ld \n",strWord,nPointer->count);}
    
    int i;
    for(i = 0; i < NUM_LETTERS; i++)
    {
    
    
    if(nPointer->children[i] != NULL)
    {
    strWord[levelTree]=nPointer->children[i]->letter;
    printWord(nPointer->children[i], strWord,levelTree + 1);
    }
    }
    }
    
    
    
    
    
    
    
    
    void printWordReverse(node* head,char strWord[], int levelTree){
    
    
    node* nPointer2 = head;
    
    
    if(nPointer2 == NULL){
    return;}
    
    
    if(nPointer2->count > 0){
    strWord[levelTree] = '\0';
    printf("%s\t %ld \n",strWord,nPointer2->count); }
    
    int i;
    for(i = NUM_LETTERS-1; i >= 0; i--)
    {
    if(nPointer2->children[i]!= NULL)
    {
    strWord[levelTree] = nPointer2->children[i]->letter;
    printWordReverse(nPointer2->children[i], strWord, levelTree + 1);
    }
    }
    
    
    }
    
    
    
    
    
    
    
    
    
    
    
    
    int isCharLeagal(char c){
    
    
    if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c == '\n' || c == ' ' || c == '\t')){
    return 1;}
    
    
    return 0;}
    Last edited by thebesthere231; 01-19-2020 at 05:07 PM.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Post your code in [code][/code] forum bbcode tags, not quote tags.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Nov 2019
    Posts
    12
    Quote Originally Posted by laserlight View Post
    Post your code in [code][/code] forum bbcode tags, not quote tags.
    ok i did it ! thanks
    can u help me plz !

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    That's good, but you should also indent your code properly. This way, it becomes easier to trace through what's happening in your code, which is precisely what you need to do in order to figure out how you ended up with a segmentation fault.

    Besides indentation, I suggest that you trim down the number of blank lines in your code. Usually, one blank line to separate logical sections of code within a function body is good enough; at file scope, you might use two consecutive blank lines to separately say, function definitions etc, but you pretty much never need more than three consecutive blank lines for anything. It just makes your code harder to read.
    Last edited by laserlight; 01-19-2020 at 05:35 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    Nov 2019
    Posts
    12
    Quote Originally Posted by laserlight View Post
    That's good, but you should also indent your code properly. This way, it becomes easier to trace through what's happening in your code, which is precisely what you need to do in order to figure out how you ended up with a segmentation fault.

    Besides indentation, I suggest that you trim down the number of blank lines in your code. Usually, one blank line to separate logical sections of code within a function body is good enough; at file scope, you might use two consecutive blank lines to separately say, function definitions etc, but you pretty much never need more than three consecutive blank lines for anything. It just makes your code harder to read.
    i tryed to do that but still i cant see my problem... becasue that i need help ...

  6. #6
    Registered User
    Join Date
    Dec 2017
    Posts
    1,626
    Your problem description is unintelligible and your code is illegible (and the header is missing). If you don't care, why should we?
    A little inaccuracy saves tons of explanation. - H.H. Munro

  7. #7
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,791
    Also, is this meant to be building a tree? If so I don't think you're doing it properly but I might be missing something because I can't read the code in its current state. Line 103 is weird as well ('a' is already an integer so why are you casting it?)

    Edit: this line is wrong
    Code:
    if( (strcmp(argv[1],r)==0) && (argc==2) )
    you should be checking that argv[1] actually points to something before trying to use it (i.e. move the argc check to the left hand side)

    Code:
    if( (argc > 1) && (strcmp(argv[1],r)==0))
    This line is also wrong:
    Code:
    strWord[levelTree] = '\0';
    But I can't look at the code any more until it's cleaned up (it's giving me a headache)
    Last edited by Hodor; 01-19-2020 at 06:35 PM.

  8. #8
    Registered User
    Join Date
    Nov 2019
    Posts
    12
    Quote Originally Posted by john.c View Post
    Your problem description is unintelligible and your code is illegible (and the header is missing). If you don't care, why should we?
    Quote Originally Posted by Hodor View Post
    Also, is this meant to be building a tree? If so I don't think you're doing it properly but I might be missing something because I can't read the code in its current state. Line 103 is weird as well ('a' is already an integer so why are you casting it?)

    Edit: this line is wrong
    Code:
    if( (strcmp(argv[1],r)==0) && (argc==2) )
    you should be checking that argv[1] actually points to something before trying to use it (i.e. move the argc check to the left hand side)

    Code:
    if( (argc > 1) && (strcmp(argv[1],r)==0))
    But I can't look at the code any more until it's cleaned up (it's giving me a headache)




    sorry for the inconvenience and thx for the help !!!
    so i need to build a tree . A tree made up of parts of nodes.
    at node have(letter,array size 26 of pointers to childs,count-(if 1=the end of the word)
    i need to build this tree from a input.txt that have there a Sentences and words , i mean i need to do
    ./(name of complite file)<input.txt
    i did the function.c and the main.c the file.h its declaration of the function

    i need to do 2 option -
    1- to print all the words In lexicographic order from large to small (that why thr "r" on argv-reverse)
    2-from small to big

    example abc bac cac
    1-cac
    bac
    abc

    2- abc
    bac
    cac

    i hope Hope it's clear now

    and why i cant edit my first post ? thx


    Code:
    // a constant definition 
    
    
    #define NUM_LETTERS 26
    
    
    typedef struct node {
    
    
        char letter;
        long unsigned int count;
        struct node* children[NUM_LETTERS];
    
    
    } node;
    
    
    
    
    // a function prototype 
    
    
    int isCharLeagal(char c);
    node* newNode();
    void buildTree(node* head);
    node* addword(node* head,node* pointNode,char character);
    int bigWordLength(node* n, int counter);
    void freeLevelsOnTree(node* head);
    void printWord(node* head,char strWord[], int levelTree);
    void printWordReverse(node* head,char strWord[], int levelTree);
    Last edited by thebesthere231; 01-19-2020 at 06:45 PM.

  9. #9
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,791
    You can only edit your first post for a certain amount of time.

    Anyway, here's your code in one file. Don't blame me if you don't like the formatting (I used AStlye to format it) or doesn't suit your style; I just needed something legible :/

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    #include <stdlib.h>
    
    #define NUM_LETTERS 26
    
    typedef struct node {
        char letter;
        long unsigned int count;
        struct node* children[NUM_LETTERS];
    } node;
    
    int isCharLeagal(char c);
    node* newNode();
    void buildTree(node* head);
    node* addword(node* head,node* pointNode,char character);
    int bigWordLength(node* n, int counter);
    void freeLevelsOnTree(node* head);
    void printWord(node* head,char strWord[], int levelTree);
    void printWordReverse(node* head,char strWord[], int levelTree);
    
    int main(int argc, char* argv[])
    {
        char* r = "r";
        node* head = newNode();
        buildTree(head);
        int biggestWordLength=bigWordLength(head, 0);
        char* word = (char*)malloc(biggestWordLength);
    
        if( (strcmp(argv[1],r)==0) && (argc==2) ) {
            printWordReverse(head,word,0);
        } else {
            printWord(head,word,0);
        }
    
        free(word);
        freeLevelsOnTree(head);
    
        return 0;
    }
    
    node* newNode()
    {
        node* n = NULL;
        n = (node*)malloc(sizeof(node));
        if (n == NULL) {
            printf("error-malloc not allocate memory");
            return NULL;
        }
        n->count = 0;
        int i;
        for (i = 0; i < NUM_LETTERS; i++) {
            n->children[i] = NULL;
        }
        return n;
    }
    
    void buildTree(node* head)
    {
        char character;
        node* pointNode = head;
    
        do {
            character = getchar();
            character = tolower(character); //Turns a big letter into a small letter lib <ctype.h>
            if(character == EOF) {
                pointNode->count++;
                return;
            }
    // if(!( character>='a' && character<='z') )
    // {continue;}
            if (!isCharLeagal(character)) continue;
            if (character == '\n' || character == ' ' || character == '\t') {
                if ( (pointNode != NULL) && (pointNode != head) ) {
                    pointNode->count++;
                    pointNode= NULL;
                }
                continue;
            }
            if(pointNode ==NULL) {
                pointNode = head;
            }
            pointNode = addword(head, pointNode, character);
        } while(character!=EOF);
    }
    
    node* addword(node* head, node* pointNode,char character)
    {
        int i = (((int)character)-((int)'a')) ; //calculate the place of the index
        if( (pointNode->children[i]) == NULL ) {
            pointNode->children[i] = newNode();
            pointNode->children[i]->letter = character;
        }
        pointNode = pointNode->children[i];
        return pointNode;
    }
    
    void freeLevelsOnTree(node* head)
    {
        node* nPointer = head;
    
        for (size_t i=0; i<NUM_LETTERS; i++) {
            if(nPointer->children[i] !=NULL) {
                freeLevelsOnTree(nPointer->children[i]);
            }
        }
        free(nPointer);
    }
    
    int bigWordLength(node* n, int counter)
    {
        int i;
        int length = counter;
    
        for(i = 0; i < NUM_LETTERS; i++) {
            if(n->children[i]!=NULL) {
                int length2 = bigWordLength(n->children[i], counter + 1);
                if(length2 > length) {
                    length = length2;
                }
            }
        }
        return length;
    }
    
    void printWord(node* head, char strWord[], int levelTree)
    {
        node* nPointer = head;
        if (nPointer == NULL) {
            return;
        }
        if (nPointer->count > 0) {
            strWord[levelTree] = '\0';
            printf("%s\t %ld \n",strWord,nPointer->count);
        }
        int i;
        for(i = 0; i < NUM_LETTERS; i++) {
            if(nPointer->children[i] != NULL) {
                strWord[levelTree]=nPointer->children[i]->letter;
                printWord(nPointer->children[i], strWord,levelTree + 1);
            }
        }
    }
    
    void printWordReverse(node* head, char strWord[], int levelTree)
    {
        node* nPointer2 = head;
        if(nPointer2 == NULL) {
            return;
        }
        if(nPointer2->count > 0) {
            strWord[levelTree] = '\0';
            printf("%s\t %ld \n",strWord,nPointer2->count);
        }
        int i;
        for(i = NUM_LETTERS-1; i >= 0; i--) {
            if(nPointer2->children[i]!= NULL) {
                strWord[levelTree] = nPointer2->children[i]->letter;
                printWordReverse(nPointer2->children[i], strWord, levelTree + 1);
            }
        }
    }
    
    int isCharLeagal(char c)
    {
        if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c == '\n' || c == ' ' || c == '\t')) {
            return 1;
        }
        return 0;
    }

  10. #10
    Registered User
    Join Date
    Nov 2019
    Posts
    12
    Quote Originally Posted by Hodor View Post
    You can only edit your first post for a certain amount of time.

    Anyway, here's your code in one file. Don't blame me if you don't like the formatting (I used AStlye to format it) or doesn't suit your style; I just needed something legible :/

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    #include <stdlib.h>
    
    #define NUM_LETTERS 26
    
    typedef struct node {
        char letter;
        long unsigned int count;
        struct node* children[NUM_LETTERS];
    } node;
    
    int isCharLeagal(char c);
    node* newNode();
    void buildTree(node* head);
    node* addword(node* head,node* pointNode,char character);
    int bigWordLength(node* n, int counter);
    void freeLevelsOnTree(node* head);
    void printWord(node* head,char strWord[], int levelTree);
    void printWordReverse(node* head,char strWord[], int levelTree);
    
    int main(int argc, char* argv[])
    {
        char* r = "r";
        node* head = newNode();
        buildTree(head);
        int biggestWordLength=bigWordLength(head, 0);
        char* word = (char*)malloc(biggestWordLength);
    
        if( (strcmp(argv[1],r)==0) && (argc==2) ) {
            printWordReverse(head,word,0);
        } else {
            printWord(head,word,0);
        }
    
        free(word);
        freeLevelsOnTree(head);
    
        return 0;
    }
    
    node* newNode()
    {
        node* n = NULL;
        n = (node*)malloc(sizeof(node));
        if (n == NULL) {
            printf("error-malloc not allocate memory");
            return NULL;
        }
        n->count = 0;
        int i;
        for (i = 0; i < NUM_LETTERS; i++) {
            n->children[i] = NULL;
        }
        return n;
    }
    
    void buildTree(node* head)
    {
        char character;
        node* pointNode = head;
    
        do {
            character = getchar();
            character = tolower(character); //Turns a big letter into a small letter lib <ctype.h>
            if(character == EOF) {
                pointNode->count++;
                return;
            }
    // if(!( character>='a' && character<='z') )
    // {continue;}
            if (!isCharLeagal(character)) continue;
            if (character == '\n' || character == ' ' || character == '\t') {
                if ( (pointNode != NULL) && (pointNode != head) ) {
                    pointNode->count++;
                    pointNode= NULL;
                }
                continue;
            }
            if(pointNode ==NULL) {
                pointNode = head;
            }
            pointNode = addword(head, pointNode, character);
        } while(character!=EOF);
    }
    
    node* addword(node* head, node* pointNode,char character)
    {
        int i = (((int)character)-((int)'a')) ; //calculate the place of the index
        if( (pointNode->children[i]) == NULL ) {
            pointNode->children[i] = newNode();
            pointNode->children[i]->letter = character;
        }
        pointNode = pointNode->children[i];
        return pointNode;
    }
    
    void freeLevelsOnTree(node* head)
    {
        node* nPointer = head;
    
        for (size_t i=0; i<NUM_LETTERS; i++) {
            if(nPointer->children[i] !=NULL) {
                freeLevelsOnTree(nPointer->children[i]);
            }
        }
        free(nPointer);
    }
    
    int bigWordLength(node* n, int counter)
    {
        int i;
        int length = counter;
    
        for(i = 0; i < NUM_LETTERS; i++) {
            if(n->children[i]!=NULL) {
                int length2 = bigWordLength(n->children[i], counter + 1);
                if(length2 > length) {
                    length = length2;
                }
            }
        }
        return length;
    }
    
    void printWord(node* head, char strWord[], int levelTree)
    {
        node* nPointer = head;
        if (nPointer == NULL) {
            return;
        }
        if (nPointer->count > 0) {
            strWord[levelTree] = '\0';
            printf("%s\t %ld \n",strWord,nPointer->count);
        }
        int i;
        for(i = 0; i < NUM_LETTERS; i++) {
            if(nPointer->children[i] != NULL) {
                strWord[levelTree]=nPointer->children[i]->letter;
                printWord(nPointer->children[i], strWord,levelTree + 1);
            }
        }
    }
    
    void printWordReverse(node* head, char strWord[], int levelTree)
    {
        node* nPointer2 = head;
        if(nPointer2 == NULL) {
            return;
        }
        if(nPointer2->count > 0) {
            strWord[levelTree] = '\0';
            printf("%s\t %ld \n",strWord,nPointer2->count);
        }
        int i;
        for(i = NUM_LETTERS-1; i >= 0; i--) {
            if(nPointer2->children[i]!= NULL) {
                strWord[levelTree] = nPointer2->children[i]->letter;
                printWordReverse(nPointer2->children[i], strWord, levelTree + 1);
            }
        }
    }
    
    int isCharLeagal(char c)
    {
        if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c == '\n' || c == ' ' || c == '\t')) {
            return 1;
        }
        return 0;
    }
    lol ok
    but what its my problem at my code and how i fix it ....
    and again thanks !!!

  11. #11
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,791
    Quote Originally Posted by thebesthere231 View Post
    lol ok
    but what its my problem at my code and how i fix it ....
    and again thanks !!!
    Well I've pointed out two problems already. Are those fixed?

  12. #12
    Registered User
    Join Date
    Nov 2019
    Posts
    12
    Quote Originally Posted by Hodor View Post
    Well I've pointed out two problems already. Are those fixed?
    no...
    so becuase i need to do 2 option of this prints i need to do args
    thats mean example the final name of the file after compile .... its ./tree
    so not i need to do 2 option
    1- to do on console /tree <inpute.txt
    2- to do on console /tree r <inpute.txt
    that why i did that

    the children on tree array in place 0- chlidren[0] its for the letter a [1]=b because that i did casting to calculate the index

  13. #13
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,791
    That's not what I'm saying. I'm saying that given this code:
    Code:
    if( (strcmp(argv[1],r)==0) && (argc==2) )  /* This is potentially accessing argv[1] when it doesn't exist */
    What happens if argc == 1? If argc == 1 (no command line options) you're still using argv[1] because && expressions are evaluated left to right. So you need to check that argc > 1 before using argv[1] (otherwise what is argv[1] which you're attempting to use in the strcmp call?) Putting the argc check on the left hand side means that the expression is "short circuited" and the strcmp doesn't happen unless there is a command line argument... which is what you want.
    I just noticed another error, that r should be inside ""

    Code:
    if( (argc > 1) &&(strcmp(argv[1], "r")==0) )

  14. #14
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,791
    Code:
    strWord[levelTree] = '\0';
    Is also wrong (as mentioned); there's no space allocated to store that '\0'

  15. #15
    Registered User
    Join Date
    Nov 2019
    Posts
    12
    Quote Originally Posted by Hodor View Post
    Code:
    strWord[levelTree] = '\0';
    Is also wrong (as mentioned); there's no space allocated to store that '\0'
    Ok the argc i understand but why the second its not true. I allocated a adress at size of the longest word that i can print and build the max array foe the other words... but i have bigger problen that the code not working sugemanation fault

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 10
    Last Post: 07-10-2012, 04:28 AM
  2. Allocate memory inside allocated memory block?
    By Heidi_Nayak in forum C Programming
    Replies: 14
    Last Post: 04-15-2009, 04:19 PM
  3. Replies: 13
    Last Post: 11-14-2008, 03:52 PM
  4. New to c++/c and dont understand the use of memory pointers
    By (Slith++) in forum C++ Programming
    Replies: 6
    Last Post: 12-19-2005, 05:30 PM
  5. help......i dont understand what i am doing wrong?
    By Grifftt in forum C Programming
    Replies: 2
    Last Post: 10-18-2002, 11:37 PM

Tags for this Thread