This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: is it possible to size a pointer's target?
- From: Tom St Denis <tstdenis at ellipticsemi dot com>
- To: Andrew Ross <grof at rogers dot com>
- Cc: gcc-help at gcc dot gnu dot org
- Date: Mon, 24 Sep 2007 06:57:41 -0400
- Subject: Re: is it possible to size a pointer's target?
- References: <001301c7fcce$ae162d60$0a00000a@ROSSAND5>
Andrew Ross wrote:
>
> Hi Everyone,
>
> I'm interested in whether it is possible to get the size of a variable a
> pointer is pointing at.
>
> I have a function that accepts a char * pointer. This can either be stack or
> heap memory but more typically stack where I see it.
>
> It would help me tremendously if I could figure out the size of the variable
> at the other end of the pointer. I can't think of a way to do this
> unfortunately.
>
> strlen won't work as the variable is null when passed in
> sizeof(*ptr) returns 1, even though the memory is larger
>
> sizeof(ptr) returns 4 (on my 32 bit machine) of course
>
> Can anyone think of how to do this, or am I out of luck?
>
This isn't a GCC question but I'll answer just the same.
The only way a function can know the length of an array pointed to by a
pointer is by the caller passing that information to the function.
Probably the best way if you want to clear up the clutter is to use a
struct which has both a pointer and length (maybe stored as an int).
Tom