PDA

Click to See Complete Forum and Search --> : Crashing help!!! [RESOLVED]


DrHippyHomer
Dec 6th, 2002, 08:51 AM
The below code causes my VB code to crash with the ' The memory could not be "read" ' error.
:mad:
BSTR WINAPI FormatID(HWND hWnd, LPCSTR sLine)
{
char *tmp = new char[strlen(sLine)];
int n;

n = <to be calculated>;
strcpy(tmp, sLine);
return BSTR(tmp[n]);
}

What I am trying to do is get the n'th character from sLine.

Any ideas, thanks in advanced.
:confused:

jim mcnamara
Dec 6th, 2002, 09:06 AM
BSTR WINAPI FormatID(HWND hWnd, LPCSTR sLine)
{
char *tmp = new char[strlen(sLine)]; <- local variable
int n;

n = <to be calculated>;
strcpy(tmp, sLine);
return BSTR(tmp[n]); <- you return a local variable
}



If you return a local volatile variable to the calling function, the memory the variable lived cannot be guaranteed to there.
Volatile means it goes away when the function returns.

Try:
Use a Global variable

Pass a pointer to the return value into the funtion

Use a static pointer in the function and malloc (one time only)
memory. You have to clean up on exit with atexit()

DrHippyHomer
Dec 6th, 2002, 09:30 AM
My code looks like :

#include <windows.h>

char *rtn;

BOOL APIENTRY DllMain(HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
return TRUE;
}

BSTR WINAPI FormatID(HWND hWnd, LPCSTR sLine)
{
//char *tmp = new char[strlen(sLine)];
int n;

n =<to be calculated>;
strcpy(rtn, sLine);
return BSTR(rtn[n]);
}

Sorry jim mcnamara could you show me the rest of what you were saying.
Cheers.
:o

crptcblade
Dec 6th, 2002, 10:11 AM
What's wrong with passing in a buffer for the character you want to get back?

CornedBee
Dec 7th, 2002, 09:26 AM
You're casting the UNICODE value of the n'th character to a pointer and return this. You have a huge memory leak. I think that's reason enough for failure...

BSTR WINAPI FormatID(HWND hWnd, LPCSTR sLine)
{
// the tmp is completly unnecessary
int n;

n = <to be calculated>;
LPWSTR str;
int iNeed = MultiByteToWideChar(CP_ACP, 0, sLine+n, 1, NULL, 0);
str = new WCHAR[iNeed];
iNeed = MultiByteToWideChar(CP_ACP, 0, sLine+n, 1, str, iNeed);
if(iNeed == 0)
{
// ERROR!
}
BSTR out = SysAllocString(str);
delete[] str;
return out;
}


This is the only correct way to return a BSTR to VB.

DrHippyHomer
Dec 9th, 2002, 03:42 AM
Many Thanks CornedBee
;)