Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What data structure does the C runtime use to store information about variable like type size etc?

Tags:

c

runtime

what data structure does the c runtime use to store information about variable like type, size etc

ex:

void foo(){
  int bar=0, goo=44;
  int*q, *p = &goo;
  //some code follows

  bar = goo + bar*9; 
  ...
  q=p;
  ... 
}

In the above code we have local variable bar and goo which will be allocated on stack when control reaches the foo function. But how will runtime determine at later point, when these variables are referenced, that these variables are of so and so type and of so and so size ?

like image 263
Jeevan Avatar asked May 25 '12 16:05

Jeevan


2 Answers

The runtime does not keep any such information - it is compiled into the binary code the compiler generates as constants. The compiler knows the size of each type, so it knows how to generate proper machine code for cleaning up the stack, accessing array elements, accessing fields of the struct, et cetera. There is no need to keep this information around at runtime, because the binary code already contains all the appropriate instructions.

like image 97
Sergey Kalinichenko Avatar answered Sep 22 '22 22:09

Sergey Kalinichenko


Variable sizes are known in compile time, so there is no need to keep them at runtime.

int bar = 0;

simply translates to

"shift the stack pointer by 4 bytes"

Variable types are neither needed to be known at all at runtime. You may get compiler warnings about incompatible types, like printing int with %c, but this is more of a sanity check for you. A variable simply names a chunk of data and it is up to you how to interpret them - as an integer, as a pointer, as 4 chars...

like image 28
Imp Avatar answered Sep 26 '22 22:09

Imp