Here's a snippet of code that IBM says is reentrant:
/* reentrant function (a better solution) */
char *strtoupper_r(char *in_str, char *out_str)
{
int index;
for (index = 0; in_str[index]; index++)
out_str[index] = toupper(in_str[index]);
out_str[index] = 0
return out_str;
}
To me this code is not reentrant because index for the loop counter is being defined locally. Should the OS interrupt this thread inside the loop, and another thread call this function, index would be lost. What am I missing? Why is this code considered reentrant?
Does the OS save a copy of local variables like index on to a thread's stack when it interrupts the thread and then reestablishes the variables when processing continues?
It seems to make this function reentrant Index would have to be part of the interface as storage provided by the caller.
index
isn't "saved" to the stack. It lives on the stack to begin with. – Dunlop