Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much memory does a C++ pointer use?

Tags:

c++

pointers

I'm making the (possibly wrong) assumption that it is implementation and/or system dependent. Is there something like INT_MAX or CHAR_BIT that would tell me the size of a pointer in memory?

like image 834
HorseloverFat Avatar asked Jul 16 '12 09:07

HorseloverFat


People also ask

How much memory does a pointer point to?

A pointer points into a place in memory, so it would be 32 bits on a 32-bit system, and 64 bits in 64-bit system.

Do pointers use more memory?

Passing a pointer to object will only increase memory consumption by the size of the pointer. Moreover it allows function to modify original object instead of a copy.

How many bytes does a pointer take in C?

Note that all pointers are 8 bytes.

How much memory does a char pointer take in C?

Consider a compiler where int takes 4 bytes, char takes 1 byte and pointer takes 4 bytes.


3 Answers

A pointer points into a place in memory, so it would be 32 bits on a 32-bit system, and 64 bits in 64-bit system.

Pointer size is also irrelevant to the type it points at, and can be measured by sizeof(anyType*)

UPD

The way I answered this was suggested by the way the question was asked (which suggested a simple answer). Yes, I do agree that in cases like pointers to virtual method table, the size of the pointer will differ, and according to this article, it will vary on different platforms and even on different compilers within the same platform. In my case, for example (x64 ubuntu, GCC 4.6.3) it equals to 16 bytes.

like image 167
SingerOfTheFall Avatar answered Oct 04 '22 02:10

SingerOfTheFall


Would sizeof(int*) work? Or whatever you're meant to be checking?

like image 35
Nathan White Avatar answered Oct 04 '22 01:10

Nathan White


It is definitely system dependant. Usually a simple data pointer can be stored in a size_t variable. In C++11 there is SIZE_MAX macro which is the maximal value for size_t. In C++11 you could also use std::intptr_t.

If you are taking member function pointers into consideration things get even more complicate. It depends among the other things if the class inherit from one or more parents, if it exposes virtual functions, and of course on the implementation.

Here you can find a detailed article about member function pointers, along with some examples for few compilers.

like image 28
Claudio Avatar answered Oct 04 '22 01:10

Claudio