title: Hacking: how to perform buffer overflow attack?
body: <p>I am stuck on a hacking exercise.</p>
  
  <p>The program shows this when executed:</p>
  
  <pre><code>Build your own string!
  
  Usage:
    ./4 length command...
  
  Each command consist of a single character followed by its index.
  
  Example:
    ./4 11 h0 e1 l2 l3 o4 w6 o7 r8 l9 d10
  </code></pre>
  
  <p>How can I perform a buffer overflow attack with command line arguments?</p>
  
  <p><code>atoi</code> converts the string argument str to an integer (type int).</p>
  
  <p><code>memset</code> copies the character c (an unsigned char) to the first n characters of the string pointed to, by the argument str.</p>
  
  <p>Thank you for your insight!</p>
  
  <pre><code>#include &lt;alloca.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdlib.h&gt;
  
  static void usage(const char *argv0) {
          printf("Build your own string!\n");
          printf("\n");
          printf("Usage:\n");
          printf("  %s length command...\n", argv0);
          printf("\n");
          printf("Each command consist of a single character followed by its index.\n");
          printf("\n");
          printf("Example:\n");
          printf("  %s 11 h0 e1 l2 l3 o4 w6 o7 r8 l9 d10\n", argv0);
          exit(1);
  }
  
  int main(int argc, char **argv) {
          char *buffer;
          unsigned short buffersize, i, index, length;
  
          if (argc &lt; 2) usage(argv[0]);
  
          length = atoi(argv[1]);
          if (length &lt;= 0) {
                  fprintf(stderr, "bad length\n");
                  return 1;
          }
  
          buffersize = length + 1;
          buffer = alloca(buffersize);
          memset(buffer, ' ', buffersize);
          buffer[buffersize - 1] = 0;
  
          for (i = 2; i &lt; argc; i++) {
                  if (strlen(argv[i]) &lt; 2) {
                          fprintf(stderr, "bad command \"%s\"\n", argv[i]);
                          return 1;
                  }
  
                  index = atoi(argv[i] + 1);
                  if (index &gt;= length) {
                          fprintf(stderr, "bad index in command \"%s\"\n", argv[i]);
                          return 1;
                  }
  
                  buffer[index] = argv[i][0];
          }
  
          printf("%s\n", buffer);
          return 0;
  }
  </code></pre>