2

I am taking an Operating Systems class and we are modifying the linux kernel.

One of my particular tasks involves creating a struct and allocating space for it. I was looking through the kernel api but couldn't seem to find a way to get the sizeof an element in kernel space.

For example, would I be able to do:

struct newNode * myNode;

myNode = (struct newNode *) kmalloc(sizeof(newNode), GFR_KERNEL);

Is "sizeof" an available command in kernel space? Or is it not accessible? If so what command should I be using instead?

crazyCoder
  • 1,552
  • 3
  • 20
  • 25
  • `sizeof` is an **operator** (there are no "commands" in C). And it's standard, and perfectly available in any kind of code. –  Oct 29 '13 at 23:54
  • Also, [do not cast the return value of `malloc()`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858). –  Oct 29 '13 at 23:54
  • @H2CO3 - What do you mean by "operator"? How's that different than a function? – matanc1 Nov 08 '13 at 11:35
  • @Shookie It's different in that it's not a function, but an operator. –  Nov 08 '13 at 12:28

1 Answers1

4

It's because you have declared no newNode to get size of.

Try sizeof(struct newNode).

Havenard
  • 27,022
  • 5
  • 36
  • 62
  • 3
    Even better: `sizeof *myNode`. –  Oct 29 '13 at 23:54
  • Altrough it works I always found this method vague for readability. I think a plain `sizeof(struct newNode)` gives immediate expression of what type you are trying to malloc there and it can be repeated for multiple variables without losing sense. It may be just me, but I think its better that way. – Havenard Oct 30 '13 at 00:05
  • 1
    And if you duplicate if several times, as you suggested, then someone changes the type of the variable but forgets to change the type in the argument of `sizeof`, then all hell breaks loose (UB). –  Oct 30 '13 at 00:08