Pointers and Dynamic Memory
In questa pagina 3
See also Puntatori in CUn puntatore contiene un indirizzo di memoria; operatori & e *, NULL, puntatori come parametri per modificare variabili del chiamante, aritmetica dei puntatori, legame tra array e puntatori, const, puntatori a puntatori.Puntatori in C →, Gestione della memoria in CSegmenti di memoria di un processo (codice, dati statici, stack, heap); durata delle variabili; allocazione dinamica con malloc, calloc, realloc e free; errori classici: memory leak, dangling pointer, double free, buffer overflow; strumenti di controllo.Gestione della memoria in C → and, for the array side, Arrays and Stringsarrays and strings in C: the equivalence between array indexing and pointer arithmetic, passing arrays to functions, string constants versus char arrays, strlen and strcpy written with pointers, multi-dimensional arrays, arrays of pointers and array initialization.Arrays and Strings →.
Pointers
A pointer is a variable that holds the memory address of another variable. Pointers store the addresses of dynamically allocated arrays and are used for arrays passed as function arguments. The size of a pointer is fixed and depends only on the architecture.
Memory is an array of consecutively numbered cells that may be handled singly or in groups: a byte can be a char, a pair of cells a short, four adjacent bytes a long. A pointer is a group of cells (often two or four) that can hold an address.
Operators
&(address of) gives the address of an object:ptr = &var;makesptrpoint tovar. It applies only to objects in memory (variables and array elements): not to expressions, constants or register variables.*(indirection, dereferencing) accesses the object a pointer points to:newVar = *ptr;copies the value ofvar.
int *ptr; // "the expression *ptr is an int"
*ptr = *ptr + 10; // *ptr can be used wherever var can
newVar = *ptr + 1; // unary * and & bind tighter than arithmetic operatorsIncrementing the pointed object:
*ptr += 1;
++*ptr;
(*ptr)++; // parentheses needed: *ptr++ would increment ptr, not what it points to(unary * and ++ associate right to left.) Pointers are variables too: ptrNew = ptr; makes ptrNew point to whatever ptr points to.
Pointers as function arguments
C passes arguments by value, so a function cannot directly change a variable of the caller. The caller passes pointers to the values to change, as in scanf("%d", &var);: a pointer argument lets a function access and modify objects of the caller. This is how exchange works in the slides:
void exchange(char* a, char* b) {
char aux;
aux = *a;
*a = *b;
*b = aux;
}Pointer rules in short
- Zero is never a valid data address:
NULLsignals failure in functions that return pointers; pointers and integers are not interchangeable (zero is the only exception). - Pointer arithmetic only within one array (plus the address one past its end); details in Arrays and Stringsarrays and strings in C: the equivalence between array indexing and pointer arithmetic, passing arrays to functions, string constants versus char arrays, strlen and strcpy written with pointers, multi-dimensional arrays, arrays of pointers and array initialization.Arrays and Strings →.
Pointers to functions
A pointer to a function stores the address of a function so it can be called indirectly; useful to pass functions as arguments or store them in data structures.
return_type (*pointer_name)(parameter_types); // declaration
int (*addPointer)(int, int); // pointer to a function taking two ints, returning int
pointer_name = &function_name; // initialization
return_type result = pointer_name(arg1, arg2, ...); // callint add(int a, int b) { return a + b; }
int (*addPointer)(int, int) = &add;
int result = (*addPointer)(3, 4);Full example: the same pointer is pointed to two functions in turn.
#include <stdio.h>
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int main() {
int (*operationPointer)(int, int);
operationPointer = &add;
printf("Result of add: %d\n", (*operationPointer)(5, 3));
operationPointer = &subtract;
printf("Result of subtract: %d\n", (*operationPointer)(5, 3));
return 0;
}Dynamic memory allocation
Memory is allocated at run time and managed through pointers, with malloc(), calloc(), realloc() (all in <stdlib.h>). It must be released explicitly with free() to prevent memory leaks.
| Function | Signature | Notes |
|---|---|---|
| malloc | void *malloc(size_t size); |
size in bytes; memory not initialized |
| calloc | void *calloc(size_t num_elements, size_t element_size); |
memory initialized to zero |
| realloc | void *realloc(void *ptr, size_t new_size); |
resizes a block from malloc or calloc |
| free | void free(void *ptr); |
returns nothing |
size_t is an unsigned integer type for sizes.
int *arr = (int *)malloc(5 * sizeof(int)); // space for 5 ints
int *arr = (int *)calloc(5, sizeof(int)); // 5 ints set to zero
arr = (int *)realloc(arr, 10 * sizeof(int)); // now room for 10 ints
free(arr);- The result is cast because these functions return a generic
void *(the exercise solution on the slides omits the cast and usessizeof(*arr)). - Failure:
mallocandcallocreturnNULLwhen memory is insufficient: always check.
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}reallocreturns a pointer to the resized block, orNULLon failure, in which case the original block is unchanged.- After
free, the pointer must not be used. Pass tofreeexactly the pointer returned by the allocator, and never free twice.
Complete example from the slides
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr1 = (int *)malloc(5 * sizeof(int)); // malloc
if (arr1 == NULL) { printf("Memory allocation failed\n"); return 1; }
int *arr2 = (int *)calloc(5, sizeof(int)); // calloc
if (arr2 == NULL) {
printf("Memory allocation failed\n");
free(arr1); // free what was already allocated
return 1;
}
arr1 = (int *)realloc(arr1, 10 * sizeof(int)); // realloc
if (arr1 == NULL) {
printf("Memory reallocation failed\n");
free(arr2);
return 1;
}
free(arr1); // deallocate
free(arr2);
return 0;
}Exercises
- Write
int *array_alloc(unsigned int n)that allocates an int array of sizen, setsarr[i] = i*iand returns the pointer. A program calls it with the size received as argument, prints the last 5 values, then frees the memory. - Read integers from stdin until EOF and store them in a growable buffer that doubles its capacity as needed.
- Allocate a buffer for sensitive data (e.g. a password), use it, then securely clear it before
free.
Solution of exercise 1 given in the slides:
#include <stdio.h>
#include <stdlib.h>
int * array_alloc (unsigned int n) {
int *arr = malloc(n * sizeof(*arr));
if (!arr) return NULL;
for (unsigned int i = 0; i < n; ++i) arr[i] = i*i;
return arr;
}(the slide shows only this function; the main program is left to the student.)
Related: Arrays and Stringsarrays and strings in C: the equivalence between array indexing and pointer arithmetic, passing arrays to functions, string constants versus char arrays, strlen and strcpy written with pointers, multi-dimensional arrays, arrays of pointers and array initialization.Arrays and Strings →, Liste concatenateLista concatenata semplice: nodi allocati dinamicamente collegati da puntatori; inserimento e rimozione in testa, scorrimento, ricerca, inserimento ordinato, deallocazione; confronto dei costi con l'array; versione in Python.Liste concatenate →, Standard Library Functionsstandard library functions used in the course beyond basic I/O: error handling with stderr, exit status, errno, perror and strerror, running commands with system, variadic functions with stdarg, and a map of the other library functions met in the slides.Standard Library Functions →, Miscellaneous Syntax - Enums, Typedef, Preprocessor and Morescope and linkage of variables, extern and header files, storage classes (auto, static, register), const and volatile, enumerations, block structure, initialization, the C preprocessor with macros and conditional compilation, and recursion.Miscellaneous Syntax - Enums, Typedef, Preprocessor and More → (const pointers).
Versione ripasso
- Pointer = variable holding an address.
&varaddress of;*ptrdereference.&does not apply to expressions, constants or register variables. int *ptr;means*ptris an int.*ptr += 1;,++*ptr;,(*ptr)++;change the pointed value;*ptr++moves the pointer.- C passes by value: to modify a caller's variable pass its address (
scanf("%d", &var),exchange(&a, &b)). NULL(zero) is the only integer assignable to a pointer; never a valid data address.- Pointer to function:
int (*p)(int, int) = &add;call(*p)(3, 4); the pointer can be re-pointed to another function of the same signature. - Dynamic memory (
<stdlib.h>):malloc(bytes),calloc(n, size)(zeroed),realloc(ptr, new_size),free(ptr). - Cast needed on the generic
void *result; allocate withn * sizeof(type)(orsizeof(*arr)). - Always check for
NULL; onreallocfailure the old block is still valid (free it, or free the other blocks, before exiting). - Free exactly the pointer given by the allocator, once, and do not use it afterwards; every allocation needs a
freeor memory leaks. - Exercise
array_alloc(n):malloc, checkNULL,arr[i] = i*i, return the pointer; the caller frees it. - Typical errors: missing
NULLcheck, use afterfree, doublefree, forgettingsizeof, leaking when an error path exits early.
See Arrays and Stringsarrays and strings in C: the equivalence between array indexing and pointer arithmetic, passing arrays to functions, string constants versus char arrays, strlen and strcpy written with pointers, multi-dimensional arrays, arrays of pointers and array initialization.Arrays and Strings → and Gestione della memoria in CSegmenti di memoria di un processo (codice, dati statici, stack, heap); durata delle variabili; allocazione dinamica con malloc, calloc, realloc e free; errori classici: memory leak, dangling pointer, double free, buffer overflow; strumenti di controllo.Gestione della memoria in C →.