Question about Pointers

Started by
6 comments, last by FrancoisSoft 20 years, 7 months ago
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!
Advertisement
4 is the size of the pointer, not the memory it is pointing to
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.
--God has paid us the intolerable compliment of loving us, in the deepest, most tragic, most inexorable sense.- C.S. Lewis
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.
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!
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.
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 

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*
--God has paid us the intolerable compliment of loving us, in the deepest, most tragic, most inexorable sense.- C.S. Lewis

This topic is closed to new replies.

Advertisement