Salta al contenuto
Note per Studenti Pointers and Dynamic Memory Report

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; makes ptr point to var. 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 of var.
c
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 operators

Incrementing the pointed object:

c
*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:

c
void exchange(char* a, char* b) {
    char aux;
    aux = *a;
    *a = *b;
    *b = aux;
}

See its use in Lab Exercises - Loops, Arrays, Structs and IOlab exercises on loops, arrays, strings, structs, enums and file input: the statements from the course slides with their hints, plus the one solution the slides give (string reversal with an exchange function).Lab Exercises - Loops, Arrays, Structs and IO →.

Pointer rules in short

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.

c
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, ...); // call
c
int 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.

c
#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.

c
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 uses sizeof(*arr)).
  • Failure: malloc and calloc return NULL when memory is insufficient: always check.
c
if (arr == NULL) {
    printf("Memory allocation failed\n");
    return 1;
}
  • realloc returns a pointer to the resized block, or NULL on failure, in which case the original block is unchanged.
  • After free, the pointer must not be used. Pass to free exactly the pointer returned by the allocator, and never free twice.

Complete example from the slides

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

  1. Write int *array_alloc(unsigned int n) that allocates an int array of size n, sets arr[i] = i*i and returns the pointer. A program calls it with the size received as argument, prints the last 5 values, then frees the memory.
  2. Read integers from stdin until EOF and store them in a growable buffer that doubles its capacity as needed.
  3. 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:

c
#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. &var address of; *ptr dereference. & does not apply to expressions, constants or register variables.
  • int *ptr; means *ptr is 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 with n * sizeof(type) (or sizeof(*arr)).
  • Always check for NULL; on realloc failure 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 free or memory leaks.
  • Exercise array_alloc(n): malloc, check NULL, arr[i] = i*i, return the pointer; the caller frees it.
  • Typical errors: missing NULL check, use after free, double free, forgetting sizeof, 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 →.

Teoria collegata