Does your S-Function use persistent variables? In C or C++ those correspond to any variable that is declared outside of any function. In C, persistent variables that are shared between compilation units would be declared "extern" in all compilation units except one; persistent variables that are local to the compilation unit would be declared "static".
When a mex function is run, it is loaded into memory, which includes allocating memory for all persistent variables; running the code leads to whatever changes to those variables made by executing the code. Initial loading can end up initializing a variable if the declaration of the variable has an initializer.
When you run the model again without having exited MATLAB and without having done "clear all" or "clear mex", then the function is not re-loaded. Persistent variables that had an initializer are not re-initialized in this case. The code will find the variables to have whatever state they had when the previous run finished.
"clear mex" causes the loaded mex function to be unloaded from memory. The next time the mex is run, it will not be present in memory and it will be loaded again, including initialization of persistent variables that had an initializer.
This behaviour of leaving persistent variables the same is not specific to MATLAB: it is the way C and C++ define persistent variables to work. It is a feature rather than a bug, since it permits hardware resource acquisition or authentication protocols to take place only once and be available for re-use when the code is executed again.
Note: if you re-create the .mex file during a session, then you should "clear mex" to force the new version to be used.
Best Answer