开发者

Static char array not found and not working with strncpy?

char *  function decode time()
{ 

   tm *ptm; //time structure
    static char timeString[STRLEN]; //hold string from asctime()

    ptm = gmtime( (const time_t *)&ltime ); //fill in time structure with ltime

开发者_JS百科    if(ptm) 
    {

       strncpy(timeString, asctime( ptm ), sizeof(timeString) ); 
//EDIT  
sprintf(test, "Sting is: %s", timeString);


       return timeString;
.
.
} //end function

When I step through the code in the debugger I I can see the value of timeString is:

timeString CXX0017: Error: symbol "timeString" not found

However, when I remove the work "static" from timeString it does fill in correctly with the string but is now a local copy and will be destroyed.

Why am I not able to copy the string from this function into a static char array?

Visual Studio 6.0 - MFC

Thanks.

EDIT the "test" string does contain the value of timeString.

I guess this is just a debugger issue? but why can't I see the value of a static array in the debugger watch?


First, function name should be function_decode_time() not function decode time()

with local static timeString will initialized entire with '\0', without static its not guaranteed without static you the return value in calling context is undefined.

strncpy will not added a '\0' in timeString for use "sizeof(timeString)" , see definition; therefore YOU must added '\0', eg:

char * functionDecodeTime()
{
  tm *ptm; /* time structure */
  static char timeString[STRLEN]; /* hold string from asctime() */

  memset( timeString, 0 , sizeof timeString ); /* entire content always is defined ! */

  ptm = gmtime( (const time_t *)&ltime ); //fill in time structure with ltime

  if( ptm )
  {
    strncpy(timeString, asctime( ptm ), sizeof(timeString)-1 );
  }

  return timeString;
}

If you use local static, your code is not reentrant/thread-safe.


Is this a Debug or Release build?

Could you use VC++ 2010 Express instead? It is free, and unless you are using the "Visual" designer or MFC it is likely to be better.

I have not used VC++ 6.0 for a long time, but a number of other debuggers I have used seem to struggle with static variables, a simple solution is this:

static char timeString[STRLEN]; //hold string from asctime()
#if _DEBUG
char* timeStringDebugRef = timeString;
#endif

Then watch timeStringDebugRef instead of timeString.


[edit]

VC++ 6.0 supports a number of debug formats with options for both the linker and the compiler (described here). Make sure that you have it configured appropriately perhaps?


0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜