I have the following code to get a string from a user with getopt()
in C:
#include <stdio.h>
#include <getopt.h>
#include "util.h"
int main(int argc, char *argv[]) {
if (argc == 1) {
usage(); // from util.h
return 0;
}
char *argument = NULL;
char ch;
while ((ch = getopt(argc, argv, ":f:"))) {
switch (ch) {
case 'f':
argument = optarg;
break;
}
}
// ... use `argument` with other stuff ...
}
Is this safe to do, or should I use strcpy()
to copy the string into argument
? If I accidentally change the contents of argument
, could an attacker change stuff like environment variables?