Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it really harmless to use sizeof(p[0]) no matter initialized or not?

Tags:

c++

sizeof

I was arguing with one of my friends, if we have defined an array/pointer:

sometype * p;

if we want to know the size of the type, he said one should use:

sizeof(sometype)

I said one could also use:

sizeof(p[0]),

it should be the same. He disagreed, and his point is if p is not initialized, then this usage of p[0] may cause problems.

But to my knowledge, only when we change or depend on the value of p[0], will this be harmful. Since we don't change p[0] nor use p[0]'s value, this is totally sensible.

Since we can't persuade each other, can anyone make this concept clear.

I know this question is of no use, and almost all the developers will use sizeof(sometype), including me :). But this question is fun and I'm really curious to know if there is any case that sizeof(p[0]) will be harmful.

=================================
Let me extend this question a little bit. If I do use some irrelevant value (or considered as kind of random or whatever). Can I always use p[0] to get a value?

To make the question more clear, If I don't change the value of an uninitialized pointer, just use the value it is pointing to, can I always get a value without causing problems?

like image 940
RainSia Avatar asked Nov 28 '22 17:11

RainSia


2 Answers

The argument to sizeof is an unevaluated operand, so pointer dereferences and so forth don't have to refer to valid memory. It's purely based on type information.

(As a corollary, sizeof *p is not polymorphic, it uses the static type only.)

like image 184
Ben Voigt Avatar answered Dec 19 '22 04:12

Ben Voigt


sizeof is evaluated at compile-time so it does not matter whether the memory is initialized or not since that's a runtime thing.

So sizeof p[0] or - what I think is even nicer since it does not look array-ish - sizeof *p is a great way to avoid typing the type again when using sizeof.

like image 44
ThiefMaster Avatar answered Dec 19 '22 05:12

ThiefMaster