Debug: the copy that writes past the end
strcpy copies characters until it reaches the terminator. It is never told how big the destination is, so if the source is longer, it writes past the end and keeps going. That is the buffer overflow, and it is still among the most exploited classes of bug in shipped software.
The fix is not to be careful. The fix is to use a function that knows the size — snprintf is the one to reach for, because unlike strncpy it always terminates the result.
On a real machine this program may well appear to work: it overwrites something nearby and carries on until that something matters. Here it stops at the moment of the write and tells you which object it ran off.
Example
char small[8]; snprintf(small, sizeof small, "%s", source); /* never writes more than 8 bytes, always terminates */
sizeof small works only where the array itself is in scope. Once it is a parameter it is a pointer, and sizeof gives the pointer size instead.
Your task
Run this first and read the error. Then make make_label safe for any input, still printing the first 15 characters of the name. Keep the same output for the short name.
- ·Do not use
strcpy— use a function that is told the size
Stuck?
Explain it
Why does this program "work" on a real machine more often than not?
Where this goes
Project 6 has you run your own code under AddressSanitizer. This is the kind of report it produces, and the reason the project insists on it.
This is a teaching runtime for a subset of C, running in your browser on a 32-bit model machine. It reports mistakes a real compiler lets through — reading uninitialised memory, running off an array, signed overflow — and it is not the compiler your project uses.
Press Run to see what your program does, or Check when you think it is right. Everything runs here in your browser.