Char* Question

T

tryptik

I am implimenting an IO function that will write numeric types (int,
long, double, etc) in binary format. I am casting them to a char* in
order to implement byte-swapping from big-endian to little-endian
before writing them out. To that end, I am using re-interperet-cast
and assigning the result to a char *. I tried to clean up the code
with a delete statement, but this seems to cause an exception.

My question is, will the memory assigned to buf be reclaimed when the
function goes out of scope? If I pass a long, buf should be pointing
to an array of size 4 - why does the delete statement cause a fault?

template <class T>
void put(T& t, std::eek:stream& s)
{
size_t size = sizeof(T);

char* buf = reinterpret_cast<char *>(&t); // Isn't buf pointing to a
char array?

//byteswap buf

s.write(buf, size);

delete [] buf; //This causes an exception - why?
}

Thanks for your help.

__tryptik
 
J

Jerry Coffin

I am implimenting an IO function that will write numeric types (int,
long, double, etc) in binary format. I am casting them to a char* in
order to implement byte-swapping from big-endian to little-endian
before writing them out. To that end, I am using re-interperet-cast
and assigning the result to a char *. I tried to clean up the code
with a delete statement, but this seems to cause an exception.

My question is, will the memory assigned to buf be reclaimed when the
function goes out of scope? If I pass a long, buf should be pointing
to an array of size 4 - why does the delete statement cause a fault?

No memory is really assigned to 'buf' - it's just a pointer that you're
setting to refer back to the original item ('t') that was passed to the
function. That means when you try to delete buf, it's trying to delete
whatever was passed into the function.

For example, if I wrote something like:

int x;

put(x, cout);

it would cause a major problem: put is going to try to delete x -- but x
wasn't allocated with new, so the best you can hope for is that your
program dies quickly with a big error message.

Use of 'delete' should match up exactly with use of 'new' and anything
that wasn't allocated with new should NOT be delete'd -- ever. Use of
new and delete should match up not only in the number of times they're
called, but also logically. For example, a typical use of new is in a
constructor for a class. The matching use of delete would be in the
destructor for the same class. A function like 'put' that has nothing to
do with allocating objects shouldn't be involved with deleting them
either.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top