I am working with some C++ code that has a timer and the timer runs this:
char buf[1024];
ZeroMemory(&buf, sizeof(buf));
somefunction(buf); // this put stuff into buf
otherfunction(buf); // this do stuff with buf
somefunction() does a web request and InternetReadFile() puts the data in “buf”
But I need to be able to read the previous buf the next time the timer is executed. How can I store buf in a global var and reassign it or make “buf” equal to the previously stored value if necessary?
If you don’t have to deal with multiple threads accessing the timer action function simultaneously, you can make
bufinto either a static variable within the scope of the function, or a file variable in the anonymous namespace (or, if you are an unreformed C programmer like me, into a file static variable). You then make sure the code does not zero the memory until you know you don’t want to look at the old data again.Either:
Or:
If nothing else needs the buffer, hiding it inside the function minimizes the scope and is the preferred solution.
If you do have multiple threads involved, you have to be extremely careful, using appropriate thread synchronization primitives to ensure sequential access to the variable, or you have to make a per-thread copy of the variable in thread local storage.