C Memory Access
In this page:
Accessing Allocated Memory
Accessing dynamically allocated memory means reading or writing the values stored at the address a pointer refers to, using either the dereference operator * or array-style square-bracket indexing.
Example: Accessing Allocated Memory
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = malloc(sizeof(int));
*ptr = 5;
printf("%d", ptr[0]);
free(ptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Dereferencing a malloc Pointer
Dereferencing with * both reads and writes to the memory that was dynamically allocated, and the allocated memory can be read and modified repeatedly through the same pointer while it remains valid.
Example: Dereferencing a malloc Pointer
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = malloc(sizeof(int));
*ptr = 10;
*ptr = *ptr + 5;
printf("%d", *ptr);
free(ptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Accessing an Allocated Array
A block of memory allocated to hold multiple elements can be accessed exactly like a regular array, using square-bracket indexing to reach each individual element within the allocated block.
Example: Accessing an Allocated Array
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = malloc(3 * sizeof(int));
arr[0] = 1; arr[1] = 2; arr[2] = 3;
printf("%d", arr[1]);
free(arr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Bounds Checking Matters
C performs no automatic bounds checking, so accessing an index beyond the allocated size compiles but produces undefined behavior, making careful tracking of allocated size the programmer's responsibility.
Example: Bounds Checking Matters
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = malloc(3 * sizeof(int));
for (int i = 0; i < 3; i++) {
arr[i] = i;
}
printf("%d", arr[2]);
free(arr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Accessing Freed Memory is Undefined
Once memory has been released with free, the pointer that referred to it becomes a dangling pointer, and dereferencing it afterward is undefined behavior since that memory may already have been reused elsewhere.
Example: Accessing Freed Memory is Undefined
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = malloc(sizeof(int));
*ptr = 5;
free(ptr);
ptr = NULL;
printf("%d", ptr == NULL);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: