newbie: getting size of pointer

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

in my code I have the following declaration:

void *buffer1;
void *buffer2;

Now, buffer1 is allocated (not shown), and its address is copied into
buffer2, like that:
buffer2 = buffer1;

After that, multiple bunches of memory are copied to buffer1, which is
incremented every time:
//here goes the copying...
(PBYTE)buffer1 = (PBYTE)buffer1 + lengthjustcopied;

Now, what I wanted to do is getting the number of all bytes that where
copied to buffer1, so I tried the following:

totalsize = (UINT)((PBYTE)userBuffer - (PBYTE)secBuffer);

This does not seem to work.... can anyone tell me what got wrong here and
how it is done correctly?

Thanks a lot
Sam Johnson
 
Hi Sam,

if I get everything right you are looking for the size of the byte array
of type void* right? So I guess this will solve your problem:

int array1size = (sizeof(buffer1)/sizeof(buffer1[0]));
int array2size = (sizeof(buffer2)/sizeof(buffer2[0]));

Just one thing: I try to avoid to work with void* so I'm not sure
whether this will work in this case too... It worked for all other types
of arrays so far, I assume it will work for void assuming this array is
byte or so.

Give it a try,

Martin
 
Hey,

there are a lot of recommendations I would love to share with you, but that
would be a too long post :)

I'll be using C++ casts not C-style casts, you should avoid C-style casts
too in C++ code. It would still work with C-stlye casts, but I wouldn't
recommend them.

The biggest problem is the way you move the buffer1 pointer. An example that
would work would be:

#define BUFF_SIZE 4096

void* pBuffer = static_cast<void*>(new char[BUFF_SIZE]);
void* pBufferStart = pBuffer;

// Here you copy to pBuffer..

// Now you move the pointer
pBuffer = static_cast<void*>(static_cast<char*>(pBuffer) + iBytesCopied);

Now you could check how many bytes you moved:

long iTotalSize = static_cast<long>(static_cast<char*>(pBuffer) -
static_cast<char*>(pBufferStart));
--

I used char* but as long as sizeof(char) == sizeof(BYTE) is equal, it
doesn't make a difference (both one bytes).

1. Why do you cast the left -side of the = operator? That makes no sense as
you don't use that value. I'm not even sure buffer1 changes in that line in
your code.
Oh, and i hope you check that you don't allow buffer overruns.. :)

2. The code i wrote is pretty ugly because of the excess amount of casts,
but I don't see why do we need to use untyped (void) pointers? Shed us some
light..

RGabo
 
Back
Top