Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is a typical buffer overflow. This is why you're always supposed to check the size of input if you're putting it in a buffer. Here is what's happening:</p> <p>In C++ (and C), array names are just pointers to the first element of the array. The compiler knows the size of the array and will do some compile-time checks. But, during runtime, it'll just treat it as a char*.</p> <p>When you did <code>cin &gt;&gt; name1</code>, you passed a char* to <code>cin</code>. <code>cin</code> doesn't know how big the allocated space is -- all it has is a pointer to some memory. So, it assumes you allocated enough space, writes everything, and goes past the end of the array. Here's a picture:</p> <pre><code>Bytes 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Before |-----name1 array-------| |--- other data-| After Q w e r t y u i o p \0 |-er data-| </code></pre> <p>As you can see, you have overwritten other data that was stored after the array. Sometimes this other data is just junk, but other times it's important and could mean a tricky bug. Not to mention, this is a security vulnerability, because an attacker can overwrite program memory with user input.</p> <p>The confusion about sizes is because <code>strlen</code> will count bytes until it finds a <code>'\0'</code> (null terminator), meaning it finds 10 characters. On the other hand <code>size(name1)</code> uses the actual size of the array, provided by the compiler.</p> <p>Because of these problems, whenever you see a C function that takes an array as an argument, it also takes the array size. Otherwise there's no way of telling how big it is. To avoid these problems, it's much better to use C++ objects like std::string.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload