Considering the following code
x = input('Input an array: ');
If the user types [1 2 3]
, variable x
will be assigned that numeric vector. Similarly, if they type {1, [2 3], 'abc'}
, variable x
will be a cell array containing those values. Fine.
Now, if the user types [sqrt(2) sin(pi/3)]
, variable x
will be assigned the resulting values: [1.414213562373095 0.866025403784439]
. That's because the provided data is evaluated by input
:
input
Prompt for user input.
result = input(prompt)
displays theprompt
string on the screen, waits for input from the keyboard, evaluates any expressions in the input, and returns the value inresult
. [...]
This can cause problems. For example, what happens if the user types addpath('c:\path\to\folder')
as input? Since the input is evaluated, it's actually a
command which will be executed by Matlab. So the user can get to add a folder to the path. Worse yet, if they input path('')
, the path will be effectively changed to nothing, and Matlab will stop working properly.
Another potential source of problems is that
[...] To evaluate expressions,
input
accesses variables in the current workspace.
For example, if the user inputs fprintf(1,'%f', varname)
and varname
is an existing numeric array, the user will know its current value.
This behaviour is probably by design. Users of a Matlab program are trusted when inputting data, much like they are trusted not to press Control-C to halt the program (and then issue all commands or inspect all variables they like!).
But in certain cases the programmer may want to have a more "secure" input
function, by which I mean
- prevent any function calls when evaluating user input; and
- prevent the input from accessing variables of the program.
So [1 2]
would be valid input, but [sqrt(2) sin(pi/3)]
or path('')
would not because of item 1; and [1 2 3 varname(1)]
would be invalid too because of item 2.