Thread: Problem with Strcmp

  1. #1
    Registered User
    Join Date
    Sep 2016
    Posts
    5

    Problem with Strcmp

    was having seg faults problems with strcmp. I think I've fixed it, but now when I'm testing files that I know are similar. It won't come out similar. Full code(Start11.c): Start11.c - Pastebin.com with its header: #ifndef START_H #define START_H #include "linkedlist.h" typedef struct temp - Pastebin.com Snipet...:
    Code:
    strcpy(location, fnames[i]);
      //Opening the files for their contents
      fpp = fopen(location, "r");
      printf("\nFile %d:[%s] \n", i+1,  fnames[i]);
    
      char* stringArray[400];
      //Reading the actual contents
      int y;
    
      for(j = 0;  fgets(info,1600,fpp) != NULL && j < 1600; j++)
      {  
          //token2
          for(token2 = strtok(info," "); token2 != NULL; token2 = strtok(NULL, " ") )
          {
            puts(token2);
            ++y;
    
            insertFront(index[i],strdup(token2)); 
            insertTemp(indexT[i],removeEnd(index[i]));
             }      
         }
       }
      //Comparisons
    
    
      int x,z,q;
    
      int count, count2;
     int groupV,groupV2;
     int value;
    
     for(x = 0; x < 300; x++)
    {
        if(indexT[0] != NULL & indexT[1] != NULL)
      {
         if(!strcmp(indexT[0], indexT[1]))
         {
            printf("similar\n");
            ++count;
            if(count == groupL)
            {
               count = 0;
               ++groupV;
            }
         }
        }
    
      }
    
     printf("\n\ngroupV %d.", groupV);
    Full code of link.c (Where my queue implementation is...:link.c - Pastebin.com with its header: #include <stdlib.h> #include <stdio.h> #ifndef LINKEDLIST_H #define LINKEDLIS - Pastebin.com )
    Thanks

  2. #2
    Registered User
    Join Date
    Sep 2014
    Posts
    364
    You should check if the file was successfully opened. Otherwise you read from a NULL-pointer.
    Your code is full of magic numbers! Fix it with #define-constant.
    The variable y isn't initialized but increased at line 16.
    The variable count isn't initialized but increased at line 39.
    The variable groupV isn't initialized but increased at line 43.

    This was only a quick look.
    It can be that your problems going away after fixing.
    I don't know, i havn't read the linked code.
    Other have classes, we are class

  3. #3
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    I would suggest using strncpy instead of strcpy. strncpy - C++ Reference

    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

  4. #4
    Registered User
    Join Date
    Sep 2016
    Posts
    5
    Thanks. Fixed those. Still having problems.
    Code:
    In file included from Start11.c:1:0:
    /usr/include/string.h:140:12: note: expected ‘const char *’ but argument is of type ‘Tem      pHold’
     extern int strcmp (const char *__s1, const char *__s2)
                ^
    Start11.c:161:10: warning: passing argument 2 of ‘strcmp’ from incompatible pointer type       [enabled by default]
              if(!strcmp(indexT[0], indexT[1]))
    Think I've pinpointed the problem now to these warnings.
    Updated code... (Made small changes to function parameters...)

    Link.c: #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> - Pastebin.com
    Start11.c (The main): Start11 - Pastebin.com
    Header for link.c: header for link - Pastebin.com
    Start.h: #ifndef START_H #define START_H #include "linkedlist.h" typedef struct temp - Pastebin.com
    And I saw something about that instead of strcmp but wasn't 100% sure if it would be better for my objective. Thinking it might be now..
    Edit: The only problem with strncpy I have is if I don't know how long the words are and if I need groupings of words. Would I just loop andstrnlen everything then...? Like this...
    Code:
    int y = 0;//count
    int  length = 0;
    for(j = 0;  fgets(info,contents,fpp) != NULL && j < contents; j++) //Has a check to make sure it isn't NULL
    
    for(token2 = strtok(info," "); token2 != NULL; token2 = strtok(NULL, " ") )
              {
                   puts(token2);
                   ++y;
                   length = length + strlen(strdup(token2));
                   if(y == groupL)
                  {
                      //Store Length dynamically allocated in my tempHold and use it in  my strnCmp?
                  }
               }
    Last edited by pyramid; 09-12-2016 at 05:26 PM.

  5. #5
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    You need to pass a string to strcmp. The elements of indexT are structs. They contain a char * member called items that you could pass to strcmp.
    Code:
    if(!strcmp(indexT[0].items, indexT[1].items))
    BTW, what is your program trying to do? If there's an online description, give the link.

  6. #6
    Registered User
    Join Date
    Sep 2016
    Posts
    5
    Quote Originally Posted by algorism View Post
    You need to pass a string to strcmp. The elements of indexT are structs. They contain a char * member called items that you could pass to strcmp.
    Code:
    if(!strcmp(indexT[0].items, indexT[1].items))
    BTW, what is your program trying to do? If there's an online description, give the link.
    Super short summary: Files are placed in a directory. I use a system command to write them into a file called inputfile.txt .
    I read inputfile.txt. From there, I open the files based on the names from inputfile.txt. I read the contents and compare for grouping of similar words. Only input user gives is the amount for groupings. Ex: 7 words."I had a black duck named Heather"

    Code:
    struct tempHold 
    {
       const char *items; 
       int size;
    };
    Changes it to const char *items
    When I start going proper to the char *items. I start getting a seg error...
    Code:
    if(!strcmp(indexT[0]->items[x], indexT[1]->items[x]))
    Warning with it...:
    Code:
    Start11.c:161:10: warning: passing argument 2 of ‘strcmp’ makes pointer from integer without a cast [enabled by default]
              if(!strcmp(indexT[0]->items[x], indexT[1]->items[x]))
              ^
    In file included from Start11.c:1:0:
    /usr/include/string.h:140:12: note: expected ‘const char *’ but argument is of type ‘char’
     extern int strcmp (const char *__s1, const char *__s2)
                ^

  7. #7
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    Now you're passing a single char. It needs to be a string. Look at my example again.

    About your program's purpose. Suppose we have the following files in the directory and the user enters the number 3. What would the output be?
    Code:
    Filename: A.txt
    one two three four
    five six seven eight
    nine ten
    
    Filename: B.txt
    alpha one two three beta
    gamma delta epsilon
    eight nine ten
    
    Filename: C.txt
    gamma delta one two
    zeta eta theta iota

  8. #8
    Registered User
    Join Date
    Sep 2016
    Posts
    5
    Quote Originally Posted by algorism View Post
    Now you're passing a single char. It needs to be a string. Look at my example again.

    About your program's purpose. Suppose we have the following files in the directory and the user enters the number 3. What would the output be?
    Code:
    Filename: A.txt
    one two three four
    five six seven eight
    nine ten
    
    Filename: B.txt
    alpha one two three beta
    gamma delta epsilon
    eight nine ten
    
    Filename: C.txt
    gamma delta one two
    zeta eta theta iota

    The problem is when I try to access it like using a . then I get an error like...
    Code:
    error: request for member ‘items’ in something not a structure or union
    If i just do indexT[0]->items I get a seg fault.
    ---
    Output based on what I have right now:
    File 1: [A.txt]
    one two three four
    five six seven eight
    nine ten
    File 2: [B.txt]
    alpha one two three beta
    gamma delta epsilon
    eight nine ten
    File 3: [C.txt]
    gamma delta one two
    zeta eta theta iota

    groupV: 0

    I see what you're saying now with the output. Because my code wouldn't recongize in File A that a pattern of three words "one two three" is the same in File B because it is going off based the order.
    I've been having trouble thinking how to store it that style. Like would I just hash it all somehow into one entry for memory purposes? or just make my search function account for that?

  9. #9
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    If you have to use ->, that's okay. The segfault is probably from dereferencing a pointer that hasn't been asssigned a valid address. Have you allocated the memory for the elements of the indexT array? Have you allocated the memory for the items strings?

    I find your code hard to understand. I'm still not sure what your program is supposed to do. With my files A.txt, B.txt, and C.txt and a user input of 3, what should the correct output be? Is it just looking for three words in a row that occur in multiple files? What's up with groupL and groupV?

    Your code may be doing too much. Does it need so much storage? What is the purpose of all the lists?

  10. #10
    Registered User
    Join Date
    Sep 2016
    Posts
    5
    Quote Originally Posted by algorism View Post
    If you have to use ->, that's okay. The segfault is probably from dereferencing a pointer that hasn't been asssigned a valid address. Have you allocated the memory for the elements of the indexT array? Have you allocated the memory for the items strings?

    I find your code hard to understand. I'm still not sure what your program is supposed to do. With my files A.txt, B.txt, and C.txt and a user input of 3, what should the correct output be? Is it just looking for three words in a row that occur in multiple files? What's up with groupL and groupV?

    Your code may be doing too much. Does it need so much storage? What is the purpose of all the lists?

    Code:
    TempHold createT(int size)
    {
        TempHold newTemp =  malloc(sizeof *newTemp);//allocate the struct
        newTemp->items = malloc(sizeof(char) * (size+1));//then allocate the array
        newTemp-> size = size;
        
        return newTemp;
    }
    Yes I believe I did right now. (Please tell me if that is not sufficient)
    Group Length is the input from user.
    Group Value is the value from count if it reaches 3. Right now, how I have it is that sequenced. I probably should have it stored instead.
    Meaning in theory if I can it to work it would give 1 group Value meaning one phrase in common if:
    one two three
    file 2:
    one two three
    but not for:
    alpha one two three
    because the sequence....
    The reason for TempHold is that when I remove it from Index it returns a string or "EMPTY" if the queue/list is empty.
    Reason why storing it is because if I want (which I need to) eventually compare file 1 to file 3. I need it stored somewhere.
    I guess I could just write another function instead of doing TempHold? Would that be better?
    Last edited by pyramid; 09-13-2016 at 08:34 AM.

  11. #11
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    I still can't understand the details of what you're trying to do. ("Right now, how I have it is that sequenced." is not a sentence.)

    And you seem unwilling or unable to tell me what the output should be with my given input files.

  12. #12
    Registered User
    Join Date
    Sep 2014
    Posts
    364
    Now i have a look at your files and see the next problem.
    You don't check if malloc was successfull.
    You hide pointer behind typedef's. This isn't realy a problem, but it confuses many reader and if you edit this code after a long time (months or years), you will be also confused.
    The name of struct linkedList is also confusing, because I don't see a linked list in your code.
    It's look for me as an array of struct linkedList. But this isn't a linked list.
    I have renamed this struct in my example to 'link_s' (the '_s'-suffix mean 'struct').
    The name of the type is also renamed to 'link_t' (the '_t'-suffix mean 'type').
    I moved the struct to the header-file.
    Befor you quit, you should free all allocated memory. Therefor, i have add a function to free 'link_t'.

    Example 'linkedlist.h':
    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #ifndef LINKEDLIST_H
    #define LINKEDLIST_H
     
    typedef int bool;
    
    typedef struct link_s
    {
       char *data;
       int key;
       int left;
       int right;
       int size;
    } link_t;
    
    link_t *createLink(int size);
    bool isFull(link_t *link);
    void insertFront(link_t *link, const char *newInfo);
    bool isEmpty(link_t *link);
    const char *removeEnd(link_t *link);
    void freeLink(link_t **link);
    
    #endif
    Example 'linkedlist.c':
    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <math.h>
    #include <string.h>
    #include "linkedlist.h"
    
    link_t *createLink(int size)
    {
        link_t *link;
    
        if ((link = malloc(sizeof (*link))) == NULL) {
            fprintf(stderr, "can't allocate link!\n");
            return NULL;
        }
    
        if ((link->data = malloc(size + 1)) == NULL) {
            fprintf(stderr, "can't allocate link->data!\n");
            free(link);
            return NULL;
        }
    
        link->size  = size;
        link->left  = 0;
        link->right = 0;
        return link;
    }
    
    void freeLink(link_t **link) {
        free((*link)->data);
        free(*link);
        *link = NULL;
    }
    You can test this functions with:
    Code:
    #include <stdio.h>
    #include "linkedlist.h"
    
    void debug_out (void *ptr) {
    if (ptr)
        printf("pointer: %p\n", ptr);
    else
        printf("pointer: (null)\n");
    }
    
    
    
    
    int main (void)
    {
        link_t *my_link = NULL;
        debug_out (my_link);
    
        my_link = createLink(int size);
        debug_out (my_link);
    
        freeLink(&my_link);
        debug_out (my_link);
    
        return 0;
    }
    Last edited by WoodSTokk; 09-14-2016 at 05:25 PM.
    Other have classes, we are class

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problem with strcmp
    By learning_grc in forum C Programming
    Replies: 2
    Last Post: 12-10-2011, 02:50 PM
  2. Is this a problem with strcmp?
    By daynorb in forum C Programming
    Replies: 6
    Last Post: 11-29-2011, 09:59 AM
  3. strcmp problem in c
    By Prodiga1 in forum C Programming
    Replies: 2
    Last Post: 11-23-2010, 12:13 AM
  4. strcmp problem, whats the problem, i cant figure it out!
    By AvaGodess in forum C Programming
    Replies: 14
    Last Post: 10-18-2008, 06:45 PM
  5. strcmp problem
    By cstudent in forum C Programming
    Replies: 3
    Last Post: 04-15-2008, 09:48 AM

Tags for this Thread