Search code examples
cmemorytypessizeof

Does sizeof returns the amount of memory allocated?


I read that:

sizeof operator returns the size of the data type, not the amount of memory allocated to the variable.

Isn't the amount of memory allocated depends on the size of the data type? I mean that sizeof will return 4 (architecture-dependent) when I pass int to it.

Am I missing something here?


Solution

  • The text you quote is technically incorrect. sizeof variable_name does return the size of memory that the variable called variable_name occupies.

    The text makes a common mistake of conflating a pointer with the memory it points to. Those are two separate things. If a pointer points to an allocated block, then that block is not allocated to the pointer. (Nor are the contents of the block stored in the pointer -- another common mistake).

    The allocation exists in its own right, the pointer variable exists elsewhere, and the pointer variable points to the allocation. The pointer variable could be changed to point elsewhere without disturbing the allocation.