Thread: printf problem

  1. #1
    Registered User
    Join Date
    Dec 2010

    printf problem

    I am making a simple program that outputs a random number but when I put a printf in it triggers a segment fault and I don't understand why. here is the code:

    #include <stdio.h>
    #include <time.h>
    int main(int argc, char *argv[]) {
        if(argc < 1 || argc > 2) {
            printf("Usage: %s [minimum value (default 0)] [maximum value]\n", argv[0]);
            return 0;
        if(argc == 1)
            printf("%d", atoi(argv[1]) % rand());
            printf("%d", (atoi(argv[2])-atoi(argv[1])) % rand() + atoi(argv[1]));
        return 0;

  2. #2
    Registered User
    Join Date
    Nov 2010
    Long Beach, CA
    You're a little confused on the value of argc. The name of the program is always the first thing in argv (argv[0]), making argc always at least 1. If I call a program with no parameters, argc is 1, if I call it with 2 parameters, argc is 3:
    $ ./foo
    argc = 1
    $ ./foo 10 20
    argc = 3
    That means, when you call it with no parameters, and argc is 1, and you try to atoi(argv[1]), which doesn't exist. When you call it with one parameter, it tries to atoi(argv[2]), which doesn't exist, and crashes. Fix your if check at the top to be argc < 2 || argc > 3, and fix your statement below to be argc == 2.

    Also, your modulus operations are backwards. You want:
    rand() % atoi(argv[1])
    // and
    rand() % (atoi(argv[2]) - atoi(argv[1])) + atoi(argv[1])

  3. #3
    Registered User
    Join Date
    Dec 2010
    ok, that fixed the problem. I should have realized that. thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problem with printf
    By raj_ksrt in forum C++ Programming
    Replies: 11
    Last Post: 07-25-2008, 11:25 AM
  2. problem with printf!!!!
    By mcaro72 in forum C++ Programming
    Replies: 6
    Last Post: 04-23-2008, 03:59 PM
  3. printf problem
    By plutoismyhome in forum C Programming
    Replies: 16
    Last Post: 09-18-2007, 06:19 PM
  4. %f printf problem
    By voodoo3182 in forum C Programming
    Replies: 6
    Last Post: 08-06-2005, 08:57 PM
  5. PRINTF problem
    By Chronom1 in forum Linux Programming
    Replies: 1
    Last Post: 07-09-2002, 11:11 PM
Website Security Test