I have written a small program that takes some input parameters from *argv[]
and prints them. In almost all use cases my code works perfectly fine. A problem only arises when I use more than one exclamation mark at the end of the string I want to pass as an argument ...
This works:
./program -m "Hello, world!"
This does NOT work:
./program -m "Hello, world!!!!"
^^ If I do this, the program output is either twice that string, or the command I entered previous to ./program.
However, what I absolutely don't understand: The following, oddly enough, DOES work:
./program -m 'Hello, world!!!!'
^^ The output is exactly ...
Hello, world!!!!
... just as desired.
So, my questions are:
- Why does this strange behavior occur when using multiple exclamation marks in a string?
- As far as I know, in C you use
""
for strings and''
for single chars. So why do I get the desired result when using''
, but not when using""
as I should (in my understanding)? - Is there a mistake in my code or what do I need to change to be able to enter any string (no matter if, what, and how many punctuation marks are used) and get exactly that string printed?
The relevant parts of my code:
// this is a simplified example that, in essence, does the same
// as my (significantly longer) code
int main(int argc, char* argv[]) {
char *msg = (char *)calloc(1024, sizeof(char));
printf("%s", strcat(msg, argv[2])); // argv[1] is "-m"
free(msg);
}
I already tried copying the content of argv[2]
into a char*
buffer first and appending a '\0'
to it, which didn't change anything.
printf("%s", strcat(msg, argv[2]))
instead ofprintf("%s", argv[2]))
?? – Chambraycalloc()
there doesn't make a lot of sense. Justchar msg[1024]
is very good. When you use the single qoutes then the string is passed as is. This has nothing to do withargv
or the c programming language, but with the shell – Assignbash
). If it is not placed in single quotes, the shell interprets!!
and replaces it with something else (the previous command in history). Your program works correctly, it prints what it receives from the shell in the command line. – Copolymerizeargc
has a valid length and checking if parameters make sense, and then probably displaying an error message with usage info. – Sauerkrautmain
being called), the c tag is not appropriate for the question and I have removed it. – Trilateration