Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a bug or something unintended with memory? [duplicate]

Tags:

c

bash

I wrote a simple C program that takes any number of text parameters and echos them out.

int main(int argc, char*argv[]){
  for (int i=1;i<argc;i++){
    for (int j=0;j<strlen(argv[i]);j++){
      printf("%c", argv[i][j]);
    }
  }
}

Running the code, it seems to be working as intended, such as

$./echo hello world
hello world

But if I add exclamation marks to the input, it goes haywire.

$./echo hello world!!
hello world./echothehelloworld

And the more exclamation marks I add at the end, it repeats to the output exponentially.

like image 577
harshk0 Avatar asked Oct 20 '25 13:10

harshk0


1 Answers

You need to escape your arguments, an unquoted or double-quoted !! gets replaced by the shell with the last command you ran, if history expansion is enabled (it is by default in an interactive shell). Aside from quoting the ! to prevent history expansion for one command, you can disable it for the current shell with set +H.

A common use of !! is to run the last command with root privileges like this:

$ whoami
marco
$ sudo !!
root

Your C code is fine, this will work as intended (note the double quotes):

$ ./echo "hello world!!"
like image 186
marco-a Avatar answered Oct 22 '25 04:10

marco-a



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!