1

this program keeps crashing instead of letting me input arguments, why?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, const char* argv[]) {
    int shift = atoi(argv[1]);
    char message[256];
    strcpy(message, argv[2]);
    int i;

    for (i = 0; i < strlen(message); i++) {
        printf("%c", message[i] + shift);
    }
    putchar('\n');

    return 0;
}

I am using codeblocks. But I also tried to run it with Notepad++. After I compiled it and when I run it it simply crashes: Name.exe has stopped working. Shouldn't it ask me to input arguments on command line?

  • On which line does it crash? – Oliver Charlesworth Sep 28 '13 at 22:56
  • in what way is it crashing? what debugging information do you have? – mfsiega Sep 28 '13 at 22:56
  • 5
    If you psss zero or one arguments on the command line, you are likely to crash. If your second arg is longer than 256 bytes, you are likely to crash. – atk Sep 28 '13 at 22:57
  • 2
    Please add an `if (argc != 3) { fprintf(stderr, "invalid number of arguments, expected 3, got %d\n", argc); abort(); }` before the call to `atoi(argv[1])`. If you get the error message, then you called the program with the wrong number of arguments. – pts Sep 28 '13 at 23:31

1 Answers1

7

A program can't possibly crash before you enter the arguments, because you need to enter the arguments before the program starts.

That is: you don't run your program like this:

Program.exe
12
hello

you need to run it like this:

Program.exe 12 hello

If you are using an IDE(you probably do), you need to configure your IDE to add the arguments. How to do that depends on which IDE you use. I assume you use Visual Studio - here is how to do it in Visual Studio: https://stackoverflow.com/a/3697320/794380

Community
  • 1
  • 1
Idan Arye
  • 12,402
  • 5
  • 49
  • 68