💻

Understanding C++ Memory and Variables

Apr 23, 2025

Machine Model I: Programming and Data Structures

Overview

  • Computer Program: Consists of source code that dictates program operations.
  • Machine Model: Helps understand the relationship between source code and runtime behavior.

Memory and Variables

  • Program Execution: Begins at main() in C++.
  • Variables: Names that refer to objects in memory which store data values.
  • Object Representation: Data stored in bytes (8 bits each).
    • Example: int uses 4 bytes, double uses 8 bytes.

C++ Memory Representation

  • Memory as Array Model:
    • Memory can be visualized as a large array with indices.
    • Variables are stored at specific indices.
    • Example: x at index 6, y at index 2, z at index 4.

Variable Initialization and Assignment

  • Copy Initialization:
    • z = x; copies value from x to z.
  • Value Modification:
    • Assignment like x = 5; changes the value of x's object.

Names, Scope, and Lifetime

  • Name Scope: Region of code where a name can be used.
  • Object Lifetime: Duration an object is valid for use.
    • Static Duration: Lifetime is the entire program.
    • Automatic Duration: Tied to a block of code.
    • Dynamic Duration: Managed by programmer.

Value vs Reference Semantics

  • Value Semantics:
    • Default in C++. Assignment copies values not references.
    • Example: x = y; copies y's value to x.
  • Reference Semantics (Initialization Only):
    • Use & to reference.
    • Example: int &y = x; makes y another name for x.

Pointers in C++

  • Address and Pointers:
    • & operator gives address of an object.
    • Pointers store addresses of objects.
    • Example: int *ptr = &x;.
  • Pointer Operations:
    • Dereferencing: Using * to access pointed object value.
    • Changing Pointer Target: Reassign a pointer to a different address.

Pointers vs References

  • References:
    • Act as another name for an object, cannot be changed once set.
  • Pointers:
    • Store address, can be reassigned, can be null.
  • Use Cases:
    • Both support access across scopes and dynamic memory.

Practical Examples

  • Swap Function with Pointers:
    • Demonstrates modifying objects across scopes using pointers.
    • Example function swap_pointed(int *x, int *y).

Conclusion

  • Pointers and references are crucial in C++ for indirect object manipulation.
  • They enable sub-type polymorphism and interaction with dynamic memory.

Note: Further exploration of dynamic memory and pointer arithmetic will be covered later in the course.