← Back to C Course | Chapter 9: Memory Management | Lesson 3 of 8

C Memory Access

Dynamically allocated memory is accessed by dereferencing the pointer with * or using array-style indexing, and C performs no automatic bounds checking, so out-of-range or use-after-free access is undefined behavior.

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

c
#include <stdio.h>
#include <stdlib.h>
int main() {
	int *ptr = malloc(sizeof(int));
	*ptr = 5;
	printf("%d", ptr[0]);
	free(ptr);
	return 0;
}

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

c
#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;
}

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

c
#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;
}

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

c
#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;
}

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

c
#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;
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.