tags:

views:

98

answers:

4

Hello,

I have a DLL written in C, which I must use. It is ok, but in one place I get an error.

int getHourTime() 
{
   struct tm *psttm;

   time_t timet = //is initialzed correctly

   psttm = localtime(&timet);

   int nHour = psttm->tm_hour;

   return nHour;
}

I am calling it in C# using DLLImport. When getting to line: "psttm->tm_hour" I get an error (throw) that "Attempted to read or write to protected memory". I understand that it is because it returns a pointer to an inner place of struct tm, but how can I solve this?

Thanks

A: 

I'm not quite sure what is going on in this case since localtime returns a pointer to statically allocated memory. Very Bad Things(tm) must be afoot for localtime to return a bad pointer. Now, if your timet struct has bad values, MSDN states a NULL value will be returned.

I think there is memory which has been trashed in your application.

Does the following work:

int getHourTime()
{
    struct tm *psttm = NULL;
    time_t timet;

    time(&timet);
    psttm = localtime(&timet);

    int nHour = psttm->tm_hour;
    return nHour;
}
sixlettervariables
Maybe "//is initialzed coorectly" is not as "coorect" as we are led to believe...
taspeotis
No, I checked this with NULL and it behaves the same.
Roman Dorevich
What is `errno` after the call to `localtime`? If `errno` is zero, then the program is trashing private memory somewhere.
sixlettervariables
A: 
int getHourTime() 
{
   struct tm *psttm;

   time_t timet = //is initialzed coorectly

   // what is psstm?  Set a breakpoint on this line and look at it
   // before and after executing localtime()
   psttm = localtime(&timet);

   // if it's non-null then you can also do this:
#if _DEBUG
   if (!HeapValidate(GetProcessHeap(), HEAP_NO_SERIALIZE, psttm)) {
       puts("bad ptr in getHourTime");
   }
#endif
   int nHour = psttm->tm_hour;

   return nHour;
}
plinth
It appears the time buffer used by `localtime` is allocated on a per thread basis using `_malloc_crt`. Is `HeapValidate` the correct one to use to make sure it isn't trashed?
sixlettervariables
+1  A: 

This has worked for me:

time_t StartTime = time(NULL);
struct tm * StartLocalTime = localtime(&StartTime);
int hour = StartLocalTime->tm_hour;

If this doesnt work, its likely you have some buffer overrun somewhere else in your code, and its just manifesting itself inside this function.

SwDevMan81
+1  A: 

The problems was because the next line :

struct tm *psttm;

It was not initialize to NULL.

Roman Dorevich