Archived

This topic is now archived and is closed to further replies.

Recommended Posts

Ok, when I allocate a buffer from the heap I usually try to use the sizeof operator to take the size of the buffer but I only get 4 when the buffer may be 1000 bytes in size. Why can''t I use sizeof on buffers allocated from the heap but I can use them on buffer allocated from the stack? Hey, don''t forget to visit my page... by clicking here!

Share on other sites
drekkar    122
4 is the size of the pointer, not the memory it is pointing to

Share on other sites
antareus    576
sizeof is evaluated at compile time, not runtime.

If you want someone to keep track of how big your buffers are then you should be using a std::vector.

Share on other sites
JonStelly    127
Or you could override the new operator and implement some sort of allocation tracking, but chances are that if you need something like that, you''re doing something else wrong.

Share on other sites
quote:
Original post by JonStelly
Or you could override the new operator and implement some sort of allocation tracking, but chances are that if you need something like that, you''re doing something else wrong.

I don''t think I want to do this.

Hey, don''t forget to visit my page... by clicking here!

Share on other sites
Well, just store the size that you''re allocating in a variable.. obviuosly you know the size that you are allocating, and the size of the data type that you''re allocating, so you know how much memory it''s using.

Share on other sites
Guest Anonymous Poster
quote:
Original post by FrancoisSoft
Ok, when I allocate a buffer from the heap I usually try to use the sizeof operator to take the size of the buffer but I only get 4 when the buffer may be 1000 bytes in size. Why can''t I use sizeof on buffers allocated from the heap but I can use them on buffer allocated from the stack?

Hey, don''t forget to visit my page... <a href="http://www.geocities.com/francoissoft">by clicking here!</a>

antareus is right. STL is easier to use.

Alternatively, you could take a page from the char string play book and have a terminating value. All you have to do is allocate 1 more than you plan to use and then write the token value in the last block.

Then sizeof is simply:
ARRAYTYPE ptr = newArray; //pointer to first elementfor(int i = 0; ptr++ != TOKEN_VALUE; i++)//the ptr is incremented to the next element after it is evaluated

Share on other sites
antareus    576
Problem is the token type should be outside the allowable range of values. This leads to silliness like a member function called getchar returning an int because it has to express failure somehow.

*cough* exceptions people, exceptions*cough*