开发者

new returns NULL when initializing static global variable in windows?

I'm working on integrating rLog with our code base, and I'm noticing a problem on Windows that I don't have on linux. In a header file I have a static variable that gives me a "verbose" logging channel (one up from debug basically), defined thusly:

static RLogChannel *rlog_verbose = DEF_CHANNEL("verbose", Log_Debug);

There's no problem with this on Linux, but on Windows I get an error as soon as the application starts.

I've tracked it down to this line in the rLog library:

RLogChannel *rlog::GetComponentChannel(const char *component, const char* path, LogLevel levl) {
...
if(!gRootChannel)
    gRootChannel = new RLogChannel( "", level );
...
}

The problem is that the call to 开发者_开发问答new is returning a NULL pointer, which goes unchecked and the program promptly crashes when it's accessed. Are there rules related to allocating memory in a global context on Windows that I'm not away of?

Edit: I'm pretty sure this must be something related to the order of initialization of static objects. I wanted to be sure that I wasn't missing something obvious re: memory allocation on Windows. Thanks all!


are you sure its returning null. It might be the whole static initializer thing. The order of static initializer invocations is not defined from file to file. If you have static code that is using rlog_verbose then gRootCHannel might well be NULL simply because the initializer hasn't been called yet.


new doesn't return NULL. it throws an std::bad_alloc exception if it fails. This happens even if its in the static data initialization which is actually called in the entry point CRT function which later calls main().

The NULL you're seeing is probably there since the new was never called. To verify that it actually gets called you can simply place a breakpoint on the static initialization and see when it occurs.


new doesn't return null. So your problem must be that you are using rlog_verbose before your static initializer executes. It's possible that your static initializer is never executing. (that would be a link problem)

You need to start up a debugger and set a break on your static initializer, and on main, and on the line of code that is crashing and just see what is happening. If you step over the crash does it work? is the crash happening before main?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜