A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
tmpnam generates a string that is a valid filename not currently in use. It does not create the file. It just gives you a name. Between the time you get the name and the time you open the file, another process could create a file with the same name. This is a TOCTOU (time-of-check-to-time-of-use) race condition. For secure temporary files, use tmpfile (which creates and unlinks atomically) or mkstemp (which creates with exclusive access). tmpnam exists for legacy compatibility.
#include <stdio.h>#include <stdlib.h>int main(void) {char name1[L_tmpnam];char name2[L_tmpnam];if (tmpnam(name1) != NULL) {printf("Temp name 1: %s\n", name1);}if (tmpnam(name2) != NULL) {printf("Temp name 2: %s\n", name2);}printf("L_tmpnam = %d\n", L_tmpnam);printf("TMP_MAX = %d\n", TMP_MAX);return 0;}
L_tmpnam is the buffer size needed to hold the generated name. TMP_MAX is the maximum number of unique names tmpnam can generate. The names are in the system's temporary directory. They are not created. You must fopen them yourself. And between tmpnam returning and your fopen call, the name is vulnerable to squatting.
Do not use tmpnam in security-sensitive code. The race condition between name generation and file creation allows symlink attacks and file pre-creation attacks. Use tmpfile() for anonymous temporary files, or mkstemp() for named temporary files with atomic creation. Both eliminate the race.
tmpnam is a relic. It exists because old code uses it. New code should use tmpfile or mkstemp. The race condition is not theoretical. It has been exploited in real vulnerabilities. Next: memmove, the overlap-safe memory copy.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.