Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Memory allocation help 1

Status
Not open for further replies.

Pyramus

Programmer
Dec 19, 2001
237
GB
Someone please tell me whats wrong with this bit of code- it compiles and runs, but it doesnt terminate properly. It still appears in task manager. It is definitely something to do with this bit.

Code:
LPWSTR output1 = pBuf->usri10_full_name;
LPWSTR output2 = pBuf->usri10_full_name;

int len1 = 0;
int len2 = 0;
int len = 0;

len1 = wcslen(output1);
len2 = wcslen(output2);

TCHAR buffer[20];

len = len1 +len2;

_itot(len,buffer,10);
MessageBox(NULL, buffer, NULL, NULL);
	
LPWSTR buf;
buf = new wchar_t [len];
	
LPWSTR o2 = wcscat(buf, output2);
o2 = wcscat(buf, output1);

MessageBox (NULL, W2T(o2), NULL, NULL);

delete [] buf;
 
LPWSTR output1 = pBuf->usri10_full_name;
LPWSTR output2 = pBuf->usri10_full_name;

Are these null terminated strings?

Matt
 
Yes. LPWSTRs have to be null terminated by definition.
 
That should be at least so:
LPWSTR output1;
LPWSTR output2;

if(pBuf) {
output1 = pBuf->usri10_full_name;
output2 = pBuf->usri10_full_name;
}
else
return; //Null Pointer

int len1 = 0;
int len2 = 0;
int len = 0;

if(output1)
len1 = wcslen(output1);
else
return; //Null Pointer
if(output2)
len2 = wcslen(output2);
else
return; //Null Pointer

TCHAR buffer[20];

len = len1 +len2;

_itot(len,buffer,10);
MessageBox(NULL, buffer, NULL, NULL);

LPWSTR buf = NULL;
//if len1 or len2 are too big, we may have len<0...
if(len >= 0)
buf = new wchar_t [len+1]; /*+1 for terminated 0! This is Your Problem */
LPWSTR o2;
if(buf) {
//Enough memory
buf[0] = 0; //Empty it - may be not all OS do it
o2 = wcscat(buf, output2);
o2 = wcscat(buf, output1);
}
else
MessageBox (NULL, &quot;Memory!&quot;, NULL, NULL);

if(buf) {
MessageBox (NULL, W2T(o2), NULL, NULL);
delete [] buf; //delete if not null
}
 
thanks a lot, great help.

Error handling aside, it was the [len+1] bit and buf[0] = 0 that was causing the probs, thanks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top