Re: A better BinaryConverter function in C++
- From: "Igor Tandetnik" <itandetnik@xxxxxxxx>
- Date: Fri, 6 Oct 2006 12:33:51 -0400
Gov <prabha.govind@microsoft(.)com> wrote:
I have this code for a binary converter function in C++...can u
suggest better way of doing it or improvements in this code...I guess
there might be better way of doing the same
string ConvertToBinary(string Msg)
{
const char * pCMsg=new char[Msg.size())];
pCMsg=Msg.c_str();
You seem to believe these two lines copy the string into a newly
allocated memory block. They do nothing of the sort. What happens is you
allocate a block of memory and store its address in pCMsg pointer. You
then promptly forget this address and overwrite it with Msg.c_str(). As
a result, pCMsg points to the string's internal storage (no copy is
made), and the allocated memory is leaked.
const char * pPath=new char[Path.size()];
pPath=Path.c_str();
Same here.
for(int i=0;i<Msg.size();i++)[snip]
{
if(pCMsg[i] & 0x80) //0x80=10000000
pMsg=1;else pMsg=0;BFile<<pMsg;
if(pCMsg[i]& 0x1) //0x1=00000001
pMsg=1;else pMsg=0;BFile<<pMsg;
You can make it
std::bitset<8> bs(pCMsg[i]);
BFile << bs;
This converts one byte at a time.
delete pCMsg;
delete pPath;
Here you are deleting memory you didn't allocate, memory that belongs to
strings Msg and Path. If you are lucky, you'll crash immediately. If you
are unlucky, these statements will corrupt the heap but allow the
application to continue execution, and you will crash hours later in a
seemingly unrelated piece of code. Good luck debugging _that_ one.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925
.
- References:
- A better BinaryConverter function in C++
- From: Gov
- A better BinaryConverter function in C++
- Prev by Date: Re: ADO Connection - "Class Not Registered"
- Next by Date: threading question
- Previous by thread: A better BinaryConverter function in C++
- Next by thread: Why does Platform SDK define union LARGE_INTEGER in such a way?
- Index(es):
Relevant Pages
|