Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to know how to copy content from wchar * to cstring safely.

wchar *buff=(wchar*)malloc(500);

cstring cbuff;

How do I copy contents of buff into cbuff so that I can destroy buff?
Posted
Updated 7-Jan-11 4:22am
v2
Comments
Dalek Dave 7-Jan-11 10:21am    
Edited for Grammar.

cstring cbuff;

if(buff && (buff[0] != 0 ))
{
  cbuff = cstring(buff);
}


Regards
Espen Harlinn
 
Share this answer
 
Did you try this:

C++
cbuff = (LPCWSTR)buff;
 
Share this answer
 
actually i m allocating memory with heapalloc
the program crashes access violation

but works if used malloc and free

Espen Harlinn and john i tried in both ways ..works if used malloc and crashes if used heapalloc

WCHAR *buff=(WCHAR*)HeapAlloc(GetProcessHeap(),0,100);
//	 WCHAR *buff=(WCHAR*)malloc(100);
 wcscpy(buff,L"rajesh");
 CString cbuff;
 cbuff=CString(buff);
  // free(buff);
   HeapDestroy(buff);
 
Share this answer
 
v2
Comments
Sandeep Mewara 7-Jan-11 11:35am    
Not an answer. Use 'Add Comment' feature to respond an answer. It will internally notify the answerer via an email about it.
ShilpiP 7-Jan-11 12:49pm    
Added code block.
Espen Harlinn 7-Jan-11 13:39pm    
Odd - you've allocated space for 50 chars, more than enough for L"rajesh"'\x00', wcscpy is in the right direction, and the CString constructor should just make another copy... - you are compiling for UNICODE?
 
Share this answer
 
First question is... why are you using malloc or an OS function (HeapAlloc) when there's new/delete built into the language? If you use new or delete you can get rid of the cast and don't have to worry about sizing arrays.

Second question is... does the code work if you use the explicit unicode specialisation of CString, CStringW? If it does then you're probably not compiling with /D_UNICODE or /DUNICODE.

Another thing to consider is whether you need to actually need to use dynamic memory in the first place. If you're just trying to sort out a buffer to do I/O then just make the buffer an automatic array and you'll find the code is far simpler and more efficient to boot.

Cheers,

Ash
 
Share this answer
 
hi ash
i m using heapalloc because i can use heaprealloc to resize it instead of deleting and creating it again if i use new.
i m compiling with _UNICODE

regards
rajesh
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900