Skip to content

Instantly share code, notes, and snippets.

@gokuldas
Created August 8, 2017 07:33
Show Gist options
  • Save gokuldas/784929fbcf24979d214d92720bad370c to your computer and use it in GitHub Desktop.
Save gokuldas/784929fbcf24979d214d92720bad370c to your computer and use it in GitHub Desktop.
Comparison of memory models of C and Python

C & Python Memory Models

Terms

  • Binding : The operation/concept of associating a memory location to a variable name
  • Indirection : The process of resolving a pointer. The modifications on an indirected pointer will be reflected in the memory location the pointer is pointing to. The pointer itself is not modified.
  • Actual : Variable in the caller function with original value
    • Variable a in both programs is the actual
  • Formal : Variable in the callee function to which the value is copied
    • Variable b inside functions of both programs is the formal

C Memory Model

  • Variable declaration is one-time BINDING to memory location
    • This include argument variables (formals) in functions
  • Variable assignment MODIFIES bound memory location
  • Function call COPIES value on actual variable to formal variable
  • Address operator (&) gets address of referred variable
  • "Call by value" and "Call by reference" are merely interpretations of above semantics
    • In call by value, actual gets copied to formal. Actual remains unchanged even when formal is modified.
    • In call by reference, address of actual is copied to formal. Formal is indirected and modified, resulting in modification of memory actual is bound to.
void modify1(int b) {
    b = 6;
}

void modify2(int* b) {
    *b = 6;
}

int main() {
    int a;
    a = 5;

    modify1(a);
    printf("Modify1: %d", a);

    modify2(&a);
    printf("Modify2: %d", a);

    return 0;
}

Python Memory Model

  • No variable declaration
  • Variable assignment RE-BINDS variable to the new object location
  • Function call BINDS the formal variable to the same memory location as actual variable
  • Methods modify object in memory, not the variable which is bound to the memory
  • Memory objects with no variable bindings get garbage collected eventually
  • There is no clear meaning for "call by value" or "call by reference"
    • Assignments to formals will result in rebinding of the formals to new objects in memory. This leaves actual objects unaltered.
    • Method calls to formals will result in modification of actuals also, since both are bound to same memory object.
def modify1(b : []):
    b = [5, 6, 7]

def modify2(b : []):
    b.append(4)

a = [1, 2, 3]

modify1(a)
print("Modify1: ", a)

modify2(a)
print("Modify2: ", a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment