c - Which memory locations to use for variable storage -


higher level languages such javascript don't give programmer choice variables stored. c does. question is: there guidelines store variables, eg dependent on size, usage, etc.

as far understand, there 3 possible locations store data (excluding code segment used actual code):

  1. data segment
  2. stack
  3. heap

so transient small data items should stored on stack?

what data items must shared between functions. these items stored on heap or in data segment. how decide choose?

you're looking through wrong end of telescope. don't specify particular memory segments in store variable (particularly since concept of "memory segment" highly platform-dependent).

in c code, decide variable's lifetime, visibility, , modifiability based on makes sense code, , based on compiler generate machine code store object in appropriate segment (if applicable)

for example, variables declared @ file scope (outside of function) or keyword static have static storage duration, meaning allocated @ program startup , held until program terminates; these objects may allocated in data segment or bss segment. variables declared within function or block without static keyword have automatic storage duration, , (typically) allocated on stack.

string literals , other compile-time constant objects (but not always!) allocated in readonly segment. numeric literals 3.14159 , character constants 'a' not objects, , not (typically) have memory allocated them; rather, values embedded directly in machine code instructions.

the heap reserved dynamic storage, , variables such not stored there; instead, use library call malloc grab chunk of heap @ runtime, , assign resulting pointer value variable allocated described above. variable live in either stack or data segment, while memory points to lives on heap.

ideally, functions should communicate solely through parameters, return values, , exceptions (where applicable); functions should not share data through external variable (i.e., global). function parameters allocated on stack, although platforms may pass parameters via registers.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -