Space complexity measures extra memory an algorithm uses beyond its input: variables, buffers, and recursion stack frames. An iterative sum uses O(1) extra space; a recursive sum uses O(n) stack because each pending call keeps a frame. In-place algorithms (reverse, swap-based sorts) keep extra space at O(1).
Remember
int sum_iter(const int *a, int n); /* O(1) extra space */
int sum_rec(const int *a, int n); /* O(n) call stack */
Reference
Cheat Sheet
Keep these facts handy while you work with Space Complexity in C.
Topic
Detail
In place
O(1) extra
Copy of input
O(n)
Recursion depth d
O(d) stack
Auxiliary
Space beyond the input
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Big O Notation in C.
Example 1 — Iterative sum versus recursive depth
Track how deep the recursion goes.
C
#include <stdio.h>
static int depth, max_depth;
static int rsum(const int *a, int n) {
depth++;
if (depth > max_depth) max_depth = depth;
int r = (n == 0) ? 0 : a[n - 1] + rsum(a, n - 1);
depth--;
return r;
}
int main(void) {
int a[] = {1, 2, 3, 4, 5};
int total = 0;
for (int i = 0; i < 5; i++) total += a[i];
printf("iterative sum=%d (one accumulator)\n", total);
int r = rsum(a, 5);
printf("recursive sum=%d, max call depth=%d\n", r, max_depth);
return 0;
}
Output
iterative sum=15 (one accumulator)
recursive sum=15, max call depth=6
How It Works
The loop needs only total and i: constant extra space.
The recursive version makes calls for n = 5, 4, 3, 2, 1, and 0.
Six frames are alive at the deepest point, so stack space grows with n.
Edge Cases & Pitfalls
Check these before relying on Space Complexity in real programs.
stack
Ignoring the call stack
Recursion looks free but each call uses stack memory and can overflow.
copy
Needless copies
Copying an array to process it doubles memory use.
Remember
Key Takeaways
Count extra memory only.
Recursion costs stack.
In place is O(1).
One line: Space complexity measures extra memory an algorithm uses beyond its input: variables, buffers, and recursion stack frames.
Frequently Asked Questions
The amount of extra memory an algorithm needs as a function of input size.
Yes. Each active call uses a stack frame, so recursion depth d costs O(d) space.
Continue with "Big O Notation in C" next. Drop constants and lower-order terms to describe growth. The C Algorithm Basics hub lists every topic in order.