I'm being faced with an unexplicable change in a variable value. Now I'm not very experienced in C, most of the code I wrote with one hand on the keyboard and the other tracking a page in K&R, so please be gentle.
I have a C project, in Visual Studio 2010, a Lua binding for the pupnp library. Here's some relevant code;
file: luaUPnPdefinitions.h (excerpt)
#ifndef LuaUPnPdefinitions_h
#define LuaUPnPdefinitions_h
...
// tracker for library being started or not
volatile static int UPnPStarted;
...
#endif /* LuaUPnPdefinitions_h */
file: LuaUPnP.h (complete file)
#ifndef LuaUPnP_h
#define LuaUPnP_h
#include "upnp.h"
#include "upnptools.h"
#include "uuid.h"
#include <lua.h>
#include <lauxlib.h>
#include "luaIXML.h"
#include "darksidesync_aux.h"
#include "luaUPnPdefinitions.h"
#include "luaUPnPsupport.h"
#include "luaUPnPcallback.h"
#endif /* LuaUPnP_h */
file: LuaUPnP.c (excerpt)
#include "luaUPnP.h" // only include in this file
...
static int L_UpnpSendAdvertisement(lua_State *L)
{
int result = UpnpSendAdvertisement(checkdevice(L, 1), luaL_checkint(L,2));
if (result != UPNP_E_SUCCESS) return pushUPnPerror(L, result, NULL);
lua_pushinteger(L, 1);
return 1;
}
...
file: LuaUPnPsupport.h (excerpt)
#ifndef LuaUPnPsupport_h
#define LuaUPnPsupport_h
//#include <ixml.h>
#include <lua.h>
#include <lauxlib.h>
#include "luaIXML.h"
#include "upnptools.h"
#include "luaUPnPdefinitions.h"
...
UpnpDevice_Handle checkdevice(lua_State *L, int idx);
...
#endif /* LuaUPnPsupport_h */
file: LuaUPnPsupport.c (excerpt)
#include "luaUPnPsupport.h" // only include in this file
...
UpnpDevice_Handle checkdevice(lua_State *L, int idx)
{
pLuaDevice dev;
luaL_checkudata(L, idx, LPNP_DEVICE_MT);
if (! UPnPStarted) luaL_error(L, UpnpGetErrorMessage(UPNP_E_FINISH));
dev = (pLuaDevice)lua_touserdata(L, idx);
return dev->device;
}
Now for the problem;
the UPnPstarted
static variable basically tracks whether the pupnp library background processes have been started.
Now when debugging at the L_UpnpSendAdvertisement
function at some point (reproducable), then UPnPstarted == 1
, but when I hit this line;
int result = UpnpSendAdvertisement(checkdevice(L, 1), luaL_checkint(L,2));
and step into it, the debugger jumps to the checkdevice
function (in file LuaUPnPsupport.c), and the value of UPnPstarted
immediately changes to UPnPstarted == 0
.
I'm lost. It's a static variable, so should be shared, why does it change value, just by stepping into that other function?
In the debugger, the watch window, the values are lit up red, indicating that they just changed. Initially I thought that the files where included in the wrong order, and the UPnPstarted
variable was duplicated (or had 2 instances), but when adding a watch to the watch window; &UPnPstarted
to track the memory location of the variable, I don't see a change when I step into the function, so it seems to me it refers to the same memory location.
I just don't get it. Any ideas on what is happening?