pointer-memoryAdress
title: "courses/c-course - pointer-memoryAdress.md"
- **fileName**: pointer-memoryAdress
- **Created on**: 2024-06-12 13:23:59
** In C, each time you run your program, the operating system assigns different memory addresses to variables due to a concept called Address Space Layout Randomization (ASLR). ASLR is a security feature that randomizes the memory addresses used by a program each time it is executed, making it harder for malicious programs to predict the locations of specific variables or functions, which enhances security by mitigating certain types of attacks.**
Why Variables Are Stored in Different Memory Locations
- ASLR (Address Space Layout Randomization): This security feature causes the memory addresses assigned to variables to change each time the program is executed.
- Stack Layout: The variables
age
,age2
,age3
,age4
, andage5
are stored on the stack. Each time the program runs, the stack may start at a different location in memory. - Memory Management by OS: The operating system's memory manager dynamically allocates stack and heap memory. This can result in different memory addresses for the same variables across different runs.
Memory Clean-up After Program Execution
When a program terminates, the operating system reclaims all the memory that was allocated to it. This means:
- Stack Memory: All stack memory (which includes local variables like
age
,age2
, etc.) is automatically cleaned up by the OS when the program exits. - Heap Memory: If your program allocates heap memory (using
malloc
,calloc
, etc.), this memory is also reclaimed by the OS when the program terminates. However, it's still a good practice to free heap memory explicitly in your program to avoid memory leaks during the program's runtime. - Global and Static Memory: These are also cleaned up by the OS when the program exits.
for accessing the memory address in c:
int myAge = 43; // Variable declaration
int* ptr = &myAge; // Pointer declaration
// Reference: Output the memory address of myAge with the pointer (0x7ffe5367e044)
printf("%p\n", &myAge);
// Dereference: Output the value of myAge with the pointer (43)
printf("%d\n", *ptr);
for accessing the value for pointer:
int* ptr = &myAge;
printf("%d", *ptr)
continue:keyword-static.md
before:rand-time.md