views:

61

answers:

2

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?

+1  A: 

If you don't have to deal with multiple threads accessing the timer action function simultaneously, you can make buf into 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:

void timer_action(void)
{
    static char buf[1024];
    ...use buf carefully...
}

Or:

namespace {
char buf[1024];
}

void timer_action(void)
{
    ...use buf carefully...
}

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.

Jonathan Leffler
A: 

Isn't something wrong if you require the old RAW data? Instead extract the pieces of interest from the current RAW buffer and store as member variables in your class. For the next read, the relevant state is available. State Design Pattern also could be helpful here if your code is about State transitions.

This will help you avoid issues related to static variables as @Jonathan pointed out

Chubsdad