Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory addressing and pointers in C

Tags:

c

This is taken from C, and is based on that. Let's imagine we have a 32 bit pointer

char* charPointer;

It points into some place in memory that contains some data. It knows that increments of this pointer are in 1 byte, etc. On the other hand,

int* intPointer;

also points into some place in memory and if we increase it it knows that it should go up by 4 bytes if we add 1 to it.

Question is, how are we able to address full 32 bits of addressable space (2^32) - 4 gigabytes with those pointers, if obviously they contain some information in them that allows them to be separated one from another, for example char* or int*, so this leaves us with not 32 bytes, but with less.

When typing this question I came to thinking, maybe it is all syntatic sugar and really for compiler? Maybe raw pointer is just 32 bit and it doesn't care of the type? Is it the case?

like image 476
Dvole Avatar asked Nov 16 '12 11:11

Dvole


1 Answers

You might be confused by compile time versus run time.

During compilation, gcc (or any C compiler) knows the type of a pointer, in particular knows the type of the data pointed by that pointer variable. So gcccan emit the right machine code. So an increment of a int * variable (on a 32 bits machine having 32 bits int) is translated to an increment of 4 (bytes), while an increment of a char* variable is translated to an increment of 1.

During runtime, the compiled executable (it does not care or need gcc) is only dealing with machine pointers, usually addresses of bytes (or of the start of some word).

Types (in C programs) are not known during runtime.

Some other languages (Lisp, Python, Javascript, ....) require the types to be known at runtime. In recent C++ (but not C) some objects (those having virtual functions) may have RTTI.

like image 94
Basile Starynkevitch Avatar answered Oct 05 '22 16:10

Basile Starynkevitch