That's a pretty good way to make demons fly out your nose, anyway...
Marcia:
"Nasal demons" is a standing joke about what could happen when someone
invokes undefined behavior.
What is undefined behavior?
In one word "Bad" it means that your program does something that might
make it:
1: Crash
2: Give incorrect results
3: Apparently work correctly (which is the worst because it could decide
to fail at the most inconvenient moment)
4: Format you harddrive (unlikely but it could happen)
5: Make demons fly out your nose (again: unlikely)
6: Anything
Ok, we've established that undefined behavior is bad, so why does Duffs
code invoke undefined behavior.
directory is now a pointer to some place in memory where there's reserved
enough space to hold 10 chars. (Length of directory plus one for a
terminating nul character)
command similarly points to 8 bytes of memory.
Now plop the contents pointed to by directory over the end of the
contens pointed to by command. Because command isn't made big enough to
hold then length of both "rm -rf " and "Directory" the memory immediately
following command will be overwritten with "irectory" and a null
character. (The 'D' occupies the space previously held by command's null
character.
Depending on what/if the memory after command was used for the program may
appear to work, or behave in unpredicatable ways. If it crashes it may
crash at a later time when that memory is used, and if nothing goes wrong
now it may do in a future version of the program (if something else uses
the moemory, or perhaps a different compiler version uses the memory
differently)
How to fix this? (untested code typed right in)
char * directory = "Directory";
char * command = "rm -rf ";
char * completed_command = malloc(strlen(directory)+strlen(command)+1);
if (!char) {
printf("Out of memory\n");
/* replace with error handling */
exit(1);
}
strcpy(completed_command,command);
strcat(completed_command,directory);
system(completed_command);
free(completed_command);