Pointers and Memory Practice for the NSCT
Pointer questions show a few lines of C or C++ and ask what they print, which address an expression holds, or why a program misbehaves. You need two skills: tracking addresses and values side by side, and knowing which memory (stack or heap) each object lives in and for how long. Programming carries 10% of the NSCT according to HEC's Areas of Competencies, and candidates averaged 47.8% accuracy in it in 2026, per the HEC NSCT report.
The official Memory Management Concepts topic covers leaks, RAII and garbage collection. This page drills the tracing. No C/C++ compiler was available, so each program was traced by hand and checked against a Python model of its memory. The Python examples were run directly. All examples assume a 64-bit system with 4-byte int, 8-byte double and 8-byte pointers, and none relies on undefined behaviour.
The method, step by step
- Draw a memory table with columns for the name, address and value. Pointers hold addresses, so write the arrow down.
&xmeans the address of x.*pmeans the value at the address in p.- Pointer arithmetic moves by elements:
p + kadds k × sizeof(*p) bytes. - Watch precedence:
*p++is*(p++), and(*p)++increments the value. - For function calls, remember that everything is copied, pointers included. Only a write through
*p(or a reference) reaches the caller. - For lifetimes, a local variable dies when its function returns. A
newormallocblock lives untildeleteorfree.
Pointer basics: & and *
int x = 25;
int *p = &x; // p holds the address of x
*p = 30; // writes through p: x is now 30
int **pp = &p; // pp holds the address of p
| Expression | Meaning | Value |
|---|---|---|
x |
the int | 30 |
&x, p, *pp |
address of x | same address |
*p, **pp |
value at that address | 30 |
&p, pp |
address of the pointer itself | a different address |
Const placement is read from right to left. const int *p cannot change the value but can move. int *const p cannot move but can change the value.
Pointer arithmetic
Worked example. int arr[] = {10, 20, 30, 40, 50}; starts at address 0x1000.
| Expression | Address | Value |
|---|---|---|
arr, &arr[0] |
0x1000 | 10 |
arr + 3, &arr[3] |
0x1000 + 3 × 4 = 0x100C | 40 |
arr + 5 (one past the end) |
0x1014 | must not be dereferenced |
After int *p = arr; p += 2;, *p is 30, p[1] is 40 and p[-1] is 20. If q = &arr[4], then q - p is 2 elements (8 bytes). A double* moves 8 bytes per step and a char* moves 1.
Worked example (increments). With int a[] = {3, 7, 11}; int *p = a;:
| Statement | Effect | Result |
|---|---|---|
int x = *p++; |
read a[0], then move p to a[1] | x = 3 |
int y = (*p)++; |
read a[1], then a[1] becomes 8 | y = 7 |
int z = ++*p; |
a[1] becomes 9, then read it | z = 9 |
Final state: a = {3, 9, 11} and p − a = 1.
2D arrays are stored row by row. In int m[3][4], m[r][c] sits (r × 4 + c) ints from the start, so m[2][1] is 9 ints (36 bytes) in. *(*(m + r) + c) is the same as m[r][c].
![Memory diagram of int arr[] = {10, 20, 30, 40, 50} starting at 0x1000 with 4-byte ints: arr + 3 points to 0x100C holding 40, and arr + 5 is one past the end at 0x1014 and must not be dereferenced.](/img/pointer-arithmetic-1200.webp)
Stack vs heap
The stack holds each function call's frame: parameters, local variables and the return address. The frame disappears automatically when the function returns. The heap holds blocks you request with new or malloc, which live until you release them.
Worked example.
int* makeSquares(int n) {
int* a = new int[n]; // a: stack; the n ints: heap
for (int i = 0; i < n; i++) a[i] = i * i;
return a; // frame popped; heap block survives
}
int main() {
int* data = makeSquares(4); // data: stack (main's frame)
int sum = 0;
for (int i = 0; i < 4; i++) sum += data[i];
delete[] data; // release the block
data = nullptr; // no dangling pointer left
}
| Object | Lives in | Dies when |
|---|---|---|
n, a, i in makeSquares |
stack | makeSquares returns |
| the 4 ints | heap | delete[] data |
data, sum |
stack | main returns |
Answer: sum = 0 + 1 + 4 + 9 = 14. If makeSquares had returned the address of a local array, the pointer would dangle after the return. Using it would be undefined behaviour.
| Stack | Heap | |
|---|---|---|
| Allocation | automatic, on function call | explicit new/malloc (or GC-managed in Java/Python) |
| Release | automatic, on return | delete/free, smart pointers or GC |
| Size | small and fixed per thread | large |
| Typical bug | stack overflow from deep recursion | leaks, dangling pointers, double free |
Passing pointers and references
void swapP(int *a, int *b) { int t = *a; *a = *b; *b = t; }
void swapV(int a, int b) { int t = a; a = b; b = t; }
With x = 3 and y = 8, swapP(&x, &y) leaves x = 8 and y = 3. swapV(x, y) leaves them unchanged, because only the copies were swapped. A C++ reference parameter (int &a) behaves like swapP with cleaner syntax. A reference can never be re-seated, so r = y copies a value.
Python: names, references and copies
Python has no pointer arithmetic, but every variable is a reference to an object.
a = [1, 2, 3]
b = a # same list
c = a[:] # new list (shallow copy)
b.append(4)
c.append(5)
print(a, b, c, a is b, a is c)
# [1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 5] True False
copy.copy shares nested objects and copy.deepcopy does not. After grid[0][0] = 99, a shallow copy shows 99 and a deep copy still shows 1.
Speed tricks
- Address of element k = base + k × size. Convert to hex at the end (16 = 0x10, 32 = 0x20).
- Pointer minus pointer = element count, never bytes.
sizeof(arr)/sizeof(arr[0])works only on a real array, not on a pointer or an array parameter.- Asterisks in declarations count levels:
int **ppneeds two dereferences to reach the int. - A function cannot change the caller's pointer unless it receives
int**orint*&.
Common mistakes
- Treating
p + 1as one byte forward for anint*. - Reading
*p++as "increment the value". - Returning the address of a local variable.
- Forgetting
delete[]for arrays allocated withnew[], or using a pointer afterdelete. - Expecting a default C++ copy to duplicate the data a pointer member points to. It copies only the address.
- Expecting
b = ain Python to copy a list.
Practice set
Use int arr[] = {2, 4, 6, 8, 10, 12}; for questions 1–4.
- With
int *p = arr + 1;, what is*(p + 2)? - If arr starts at address 500, what is
&arr[5]? - With
int *s = arr, *e = arr + 5;, what ise - s? - What is
sizeof(arr) / sizeof(arr[0])? - After
int x = 7; int *p = &x; *p = 10;, what is x? - What is
sizeof(double*)on the assumed system? - Python:
t = (1, [2, 3]); t[1].append(4); print(t). What happens? - What is
sizeofofchar s[] = "PAK";? - Which one leaks memory:
int *p = new int(5); p = new int(6);orint *p = new int(5); delete p; p = new int(6);?
Show answers
- 8. p is at arr[1], so p + 2 is arr[3].
- 520. 500 + 5 × 4.
- 5 elements.
- 6.
- 10.
- 8 bytes. All object pointers are 8 bytes here, whatever they point to.
- It prints
(1, [2, 3, 4]). The tuple is immutable, but the list inside it is not. - 4. Three characters plus the terminating
'\0'. - The first. The block holding 5 loses its only pointer.
Practise: 20 questions
FAQs
Why does p + 1 skip 4 bytes instead of 1?
Because pointer arithmetic works in elements, not bytes. The compiler knows p points to an int, so p + 1 means "the next int", which is sizeof(int) bytes further. To step one byte at a time, convert to char* (or unsigned char*), whose element size is exactly 1.
Is an array the same as a pointer?
No, but an array name converts (decays) to a pointer to its first element in most expressions. The differences show with sizeof (whole array versus one pointer) and &arr (address of the whole array, a different type). You also cannot assign to an array name, while a pointer can be re-pointed.
Does Java have pointers?
Java has references, which are pointers without arithmetic. You cannot take an address, add to it or free memory manually; the garbage collector reclaims unreachable objects. NullPointerException is the Java equivalent of dereferencing a null pointer. Local reference variables live on the stack and the objects they refer to live on the heap, much like a C++ pointer to a new object.
What is the difference between a dangling pointer and a memory leak?
A dangling pointer still holds an address whose memory has been freed or gone out of scope, so using it is undefined behaviour. A leak is the opposite: the memory is still allocated, but no pointer to it remains, so it can never be freed. Smart pointers such as std::unique_ptr prevent both.
Next step
Go back to the official Memory Management topic, then practise class hierarchies in OOP code questions. See all topics on the Programming MCQs hub, or try an NSCT mock test.