Thread: Help with strlen and passing arguments into the main!

  1. #1
    Registered User
    Join Date
    Mar 2016
    Posts
    4

    Help with strlen and passing arguments into the main!

    Hello, firstly I am new here and if this question is posted in a wrong way, please do suggest me to modify it as per the needs of the community here.

    Anyway, I am trying to print the string length of the first argument that is passed to main. Here is the code.

    Code:
    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    #include<error.h>
    
    
    int main(int argc, char* argv[])
    {
        FILE* fp;
        fp=stdin;
        char* filename=stdin;
        char* searchString=NULL;
        if(argc>1)
        {
            int i=1;
            for(i=1;i<argc;i++)
            {
                switch(i)
                {
                    case 1:
                    searchString=(char*)malloc((int)(strlen(argv[i]))*sizeof(char));
                    memcpy(searchString,argv[i],strlen(argv[i]));
                    break;
                    case 2:
                    filename=(char*)malloc((int)strlen(argv[i])*sizeof(char));
                    strcpy(filename,argv[i]);
                    fp=fopen(argv[i],"r");
                    if(fp==NULL)
                    {
                        exit(EXIT_FAILURE);
                    }
                    break;
                    default:
                    break;
                }
            }
            
        }
        else
        {
            printf("Usage: fgrep [OPTION]... PATTERN [FILE]...\n");
            printf("Try './mygrep --help' for more information.\n");//need to implement this yet
        }
        printf("%d\n",strlen(searchString));
        return 0;        
    }

    In linux terminal, after compiling when I run the command,
    ./nameofProgram abcdefghijk filename.txt, I am getting the correct output i.e., 11 as my string length of the string "abcdefghijk", but when I input the string as "abcdefghijkl", i get the output as 13 instead of 12. So how do I solve it?

    Thanks

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    You're not allocating enough space for your strings - you need to include room for the string-terminating null character ('\0').
    Ditto on the memcpy.

    A few other notes:

    • Don't cast "malloc()"
    • You should check that your "malloc()" calls have succeeded before attempting to access that memory
    • In the "malloc()" calls, you don't need "sizeof(char)" - it is guaranteed to be 1
    • You need to free allocated memory when you're done with it
    • You should close the file when you're done with it

  3. #3
    Registered User
    Join Date
    Mar 2016
    Posts
    4
    So I just need to increase the size by 1 for that extra null character right? and could you please show the code for malloc() and malloc() checking that you have mentioned. Thanks

  4. #4
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    >> So I just need to increase the size by 1 for that extra null character right?

    Correct.

    >> and could you please show the code for malloc() and malloc() checking that you have mentioned. Thanks

    When malloc fails, it returns a NULL pointer. So you just need to check for that. (Hint: you do a similar check after calling "fopen()".)

  5. #5
    Registered User
    Join Date
    Mar 2016
    Posts
    4
    Oh ok, thanks, but one last question, what do I need to do when a malloc fails? I mean should I just exit out and maybe printf a statement to the stdout saying that its an error or do I need to do anything else? I know it would depend on my programming preference and the problem at hand, but there are certain programming practices that are considered best in such cases right? like writing to stderror or something? If yes, how do I do that? There is something called ferror or perror or strerror or errno or something right? Thanks

  6. #6
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    What actions to perform largely depend on the context of the code. In a large program, you likely don't want to exit the program if a malloc call fails, since the program would still be able to perform other actions. For a small program, where the entire functionality relies on that memory, then exiting might be a more appropriate strategy.

    Either way, reporting the problem to the user is a good idea. For a program like this, a simple printf should be sufficient. You could also print to stderr in case the user is redirecting stdout, but I don't think this is too big of a concern if you're just starting out. errno might be overkill for such simple applications.

    If you do decide to exit the program on failure, though, be sure that any clean-up is handled properly (e.g. freeing previously allocated memory, closing files, etc) first.

  7. #7
    Registered User
    Join Date
    Mar 2016
    Posts
    4
    Oh ok. Thanks a lot. One last question. How do I close this thread now that my problem has been solved? Thanks

  8. #8
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    You're welcome.

    There is no way to mark a thread as "solved" here, we just let them sink into the background (though they are automatically closed after a few weeks of inactivity).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing arguments to main
    By drkidd22 in forum C Programming
    Replies: 1
    Last Post: 02-10-2015, 10:31 AM
  2. Trouble passing a string into strlen()...
    By yaya in forum C++ Programming
    Replies: 4
    Last Post: 01-08-2008, 04:46 AM
  3. Passing arguments to main?
    By xddxogm3 in forum C++ Programming
    Replies: 4
    Last Post: 10-16-2003, 03:59 AM
  4. strlen() and passing by address
    By supaben34 in forum C++ Programming
    Replies: 2
    Last Post: 07-12-2003, 01:49 PM
  5. passing strings and using strlen
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 09-15-2001, 10:41 PM

Tags for this Thread