Re: sizeof *data, when data isn't initalized, is that right?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 01/22/15 13:39, Hubert CHAUMETTE wrote:
> As I understand it, sizeof(*data) is the same as sizeof(struct mcp23s08_driver_data). There should be no pointer dereference here, so I would say it isn't an issue.

In most cases (always?) sizeof() is a compile-time operator; it is up to
the compiler to perform the calculation of an object's size and simply
place that constant into the code. This is why the target of a sizeof()
operation needs to be fully defined at compile time.

Therefore, since this calculation takes place at compile time, there is
no run-time pointer dereference taking place.


>  That notation is quite confusing though.

This idiom is quite common, so it would be good to become familiar with
it. Without using this idiom one would have to write:

    sizeof (struct mpc23s08_driver_data)

which is fine... until someone else comes along and changes "data"'s
type (defined way up at the start of the function) to, say,
mpc23s08_driver_data_2. Then someone would need to go through all the
code and find all instances of

    sizeof (struct mpc23s08_driver_data)

and change all of them to

    sizeof (struct mpc23s08_driver_data_2)

As you might guess, this is prone to error. However, if the original
developer used

    sizeof (*data)

throughout their code, no such subsequent changes would be needed. The
compiler is smart enough to figure out that *data is an object of struct
mpc23s08_driver_data and use that in its sizeof calculation. If/when
"data"'s definition gets changed, the compiler is then able to use
mpc23s08_driver_data_2 in its calculation, without any necessary
subsequent changes to the code.
--
To unsubscribe from this list: send the line "unsubscribe linux-c-programming" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html




[Index of Archives]     [Linux Assembler]     [Git]     [Kernel List]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [C Programming]     [Yosemite Campsites]     [Yosemite News]     [GCC Help]

  Powered by Linux