Thread: Help needed to debug

  1. #1
    Registered User
    Join Date
    Nov 2020
    Posts
    24

    Help needed to debug

    I wrote this code but cannot figure out the issues that arise when trying to compile.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    int find_First_Letter (char **word_Array, int num_words); /*Function to find the first letter of a string*/
    
    
    int main (void){
        FILE *in, *out;
        int num_words, num_letters, x, y;
        
        in = fopen("alphabetic_sort.dat", "r");
        out = fopen("alphabetic_sort.out", "w");
        
        if (in == NULL || out == NULL)       /*Check to see whether files can be openned or not*/
        {
            printf("Error opening files!\n");
            fclose(in);
            fclose(out);
            return -1;
        }
    
    
        char **wordArray, c = '\0';
        fscanf(in, "%d", &num_words);
        wordArray = (char*) malloc(num_words*sizeof(char));   /*Creates memory for every word*/
        for(x = 0; x<num_words; x++){
            fscanf(in, "%d ", &num_letters);
            (wordArray + x) = (char) malloc((num_letters + 1)*sizeof(char)); /*Creates memory for every letter in the word. +1 due to null character at the end*/
            for (y = 0; y < num_letters; y++)
            {
                while (!((c >= 'a' && c <= 'z') || c == '\n'))   
                {
                    fscanf(in, "%c", &c);
                }
                if (c == '\n')
                {
                    ((wordArray + x) + y) = '\0';  /*Sets newline to a null character*/
                }else{
                    ((wordArray + x) + y) = c;
                }
                
                c = '\0';  /*c is set to a null character*/
            }
            
        }
    
    
        int word_index;
        char *sortedwordArray = (char) malloc(num_words * sizeof(char));  /*Memoery is allocated according to the number of words inputted*/
        
        for (x = 0; x < num_words; x++)
        {
            word_index = find_First_Letter(wordArray, num_words);
            sortedwordArray[x] = wordArray[word_index];
            wordArray[word_index] = NULL
        }
        
        for (x = 0; x < num_words; x++)
        {
            fprintf(out, "%s\n", sortedwordArray[x]); /*Output gets printed to the required file*/
        }
        
        for (x = 0; x < num_words; x++)
        {
            free(*(wordArray + x));  /*Frees the memory preventing memory leaks*/
        }
        
        fclose(in);   /*Closes input file*/
        fclose(out);  /*Closes output file*/
    
    
        return 0;
    
    
    }
    
    
    int find_First_Letter (char **word_Array, int num_words){
        int i, word_index;
        char *First_Word;
        word_index = 0;
        
        for (i = 0; i < num_words; i++)   /*Find the first non-null pointer*/
        {
            if (word_Array[i] != NULL )
            {
                First_Word = word_Array[i];
                word_index = i;
                break;
            }
            
        }
        
        for (i = word_index + 1; i < num_words; i++)
        {
            if (word_Array[i] == NULL)   /*Null characters are to be ignored*/
            {
                continue;
            }
            else if (strcmp(First_Word, word_Array[i]) > 0)   /*Compare two strings to find if the current word is a higher value*/
            {
                First_Word = word_Array[i];
                word_index = i;
            }
            
        }
        
        return word_index; 
    }

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    STOP casting the result of malloc when programming in C.

    If you have a compile error; post the error!!

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  3. #3
    Registered User
    Join Date
    Nov 2020
    Posts
    24
    Could you kindly please explain what casting the result of malloc means?

  4. #4
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Casting malloc - Cprogramming.com

    Edit: And, you are casting it wrong even for C++ in at least two places!

    This below is considered improper; but, will likely work most of the time.
    Code:
    (char*) malloc(
    This below is wrong and is likely to never work!
    Code:
    (char) malloc(
    Tim S.
    Last edited by stahta01; 12-19-2020 at 05:19 AM.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  5. #5
    Registered User
    Join Date
    Nov 2020
    Posts
    24
    I did what you mentioned but it is still not working. Sorry for causing you inconvenience.

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Part of learning to program is learning how to fix errors. To learn that, you need to pay attention to the errors. You can start by posting them here and telling us what do you think they mean.

    I could of course just compile and fix your program, but then you won't learn anything.
    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

  7. #7
    Registered User
    Join Date
    Nov 2020
    Posts
    24
    @laserlight
    When trying to compile these are the errors I am facing. Unsure of how to fix them.

    In function ‘main’:
    main.c:31:15: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
    wordArray = (char*) malloc(num_words*sizeof(char)); /*Creates memory for every word*/
    ^
    main.c:34:25: error: lvalue required as left operand of assignment
    (wordArray + x) = (char*) malloc((num_letters + 1)*sizeof(char)); /*Creates memory for every letter in the word. +1 due to null character at the end*/
    ^
    main.c:43:39: error: lvalue required as left operand of assignment
    ((wordArray + x) + y) = '\0'; /*Sets newline to a null character*/
    ^
    main.c:45:39: error: lvalue required as left operand of assignment
    ((wordArray + x) + y) = c;
    ^
    main.c:59:28: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
    sortedwordArray[x] = wordArray[word_index];
    ^
    main.c:61:5: error: expected ‘;’ before ‘}’ token
    }
    ^
    main.c:65:24: warning: format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘int’ [-Wformat=]
    fprintf(out, "%s\n", sortedwordArray[x]); /*Output gets printed to the required file*/
    ^

  8. #8
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Stop casting the return value of malloc, you are causing several errors with those casts.

    Next what do you think (wordArray + x) is actually accomplishing?

    Why aren't you using "normal" array notation instead of trying to confuse yourself by trying to use array notation?

    Make sure all of your source lines are properly terminated.

    Again stop casting the return value of malloc, doing so usually just hides problems.

  9. #9
    Registered User
    Join Date
    Nov 2020
    Posts
    24
    I don't understand what you mean by me casting the return value of malloc.

  10. #10
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Do you know what casting means and how it's done in C?

    This contains a cast of the return value of malloc(): wordArray = (char*) malloc(10), note the highlight.

  11. #11
    Registered User
    Join Date
    Nov 2020
    Posts
    24
    I understand what you are trying to get at but what exactly is my mistake? Please bear with me.

  12. #12
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Well in several places you are casting the return value to the wrong type, for example a char instead of a char*. Since you use a cast the compiler is free to deduce that you know what you're doing and not report any issues with the cast. Remember casting is inherently dangerous and should be used with the upmost caution, and avoided whenever possible.

  13. #13
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,110
    Quote Originally Posted by Timmy10 View Post
    I don't understand what you mean by me casting the return value of malloc.
    Code:
       char *ptr = NULL;
       ptr = malloc(64);
       // NOT
       ptr = (char *) malloc(64);
    malloc() returns a "void *" (Generic typeless pointer) which can be, and should be, assigned to a pointer of any data type without casting.

  14. #14
    Registered User
    Join Date
    Nov 2020
    Posts
    24
    Quote Originally Posted by jimblumberg View Post
    Well in several places you are casting the return value to the wrong type, for example a char instead of a char*. Since you use a cast the compiler is free to deduce that you know what you're doing and not report any issues with the cast. Remember casting is inherently dangerous and should be used with the upmost caution, and avoided whenever possible.
    So I should never cast? Like is that a bad practice?

  15. #15
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,110
    Quote Originally Posted by Timmy10 View Post
    So I should never cast? Like is that a bad practice?
    Yes.
    Code:
    char *sortedwordArray = (char) malloc(num_words * sizeof(char));
    sortedwordArray is a char *
    malloc() returns a void *
    You are casting a void * to a char (Not a pointer) then assigning to a char *!!! WRONG!!!

    The following would have been legal but not recommended!
    Code:
    char *sortedwordArray = (char *) malloc(num_words * sizeof(char));
    In almost all cases, please avoid casting a return from malloc()

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Debug error, help needed
    By wsy in forum C++ Programming
    Replies: 10
    Last Post: 08-11-2006, 06:19 PM
  2. debug dll
    By axr0284 in forum C++ Programming
    Replies: 3
    Last Post: 03-06-2006, 04:52 PM
  3. Debug help needed
    By Achy in forum C Programming
    Replies: 3
    Last Post: 11-16-2005, 03:27 PM
  4. using DEBUG - hopefully
    By darfader in forum C Programming
    Replies: 1
    Last Post: 08-12-2003, 05:21 AM
  5. How do you like to debug?
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 23
    Last Post: 12-12-2002, 10:23 PM

Tags for this Thread