Tuesday, February 22, 2022

[SOLVED] Why in kernel code some addresses of variables are stored in char pointers?

Issue

I was going through the kernel source code and I found this statement:

char *tagp = NULL;

/* ...CODE... */

tagp = &descriptor->b_data[sizeof(journal_header_t)];

I wonder why this address is stored in a char pointer rather than any other type more related to what it represents, such as maybe void if this is an opaque.


Solution

The individual cases may have their explicit use-cases, but in general, this is useful for two reasons.

  • a char pointer has the same alignment requirement as a void pointer.
  • char pointer can be used to access (via dereference) any other type of data, starting from lowest addressed byte of the object (Successive increments of the result, up to the size of the object, yield pointers to the remaining bytes of the object.). Also, pointer arithmatic (if needed, is allowed on char pointer, not on void pointers).

Thus, using a char * is more robust.



Answered By - Sourav Ghosh
Answer Checked By - Timothy Miller (WPSolving Admin)