Aller au contenu

Exemples sur la mémoire

Cette section contient des exemples liés à la gestion de la mémoire en C. Voici la liste des fichiers sources, avec leur description et un lien vers leur contenu.

Fichier Description Lien
memory_01.c Illustre l'obtention de la taille de page de la mémoire virtuelle Voir
memory_02.c Montre la carte mémoire d'un processus simple Voir
memory_03.c Montre la carte mémoire d'un processus utilisant une bibliothèque dynamique Voir
memory_04.c Allocations sur le tas à observer dans la carte mémoire (/proc/<PID>/maps sous Linux, vmmap <PID> sous macOS) ; un arrêt par Ctrl-C avant free() n'est pas une vraie fuite (voir memory_05a.c pour en avoir une) Voir
memory_05a.c Illustre un problème de fuite mémoire dans un autre contexte Voir
memory_05b.c Montre en complément comment éviter un problème de fuite mémoire Voir
memory_06.c Affiche l'organisation complète de la mémoire d'un processus (texte, données, BSS, tas, pile) à l'aide des symboles externes etext, edata, end (sous macOS : get_etext(), get_edata(), get_end(), que le compilateur signale comme obsolètes : les avertissements sont attendus) Voir
memory_07.c Donne un aperçu de l'utilisation de la mémoire de la pile Voir
mmap1.c Projette un fichier en mémoire avec mmap() (taille obtenue par fstat() sur le descripteur ouvert), l'écrit sur le terminal, puis lit la projection comme un tableau Voir
mmap2.c Illustre la projection d'un fichier sur un segment de mémoire avec une autre approche Voir
page_size.c Affiche la taille de page avec la fonction POSIX sysconf(_SC_PAGESIZE) (variante POSIX de memory_01.c) (cours, chapitre "Mémoire virtuelle") Voir
mmap_toupper.c Modifie un fichier sur place au travers d'une projection MAP_SHARED (le convertit en majuscules) (cours, chapitre "Mémoire virtuelle") Voir
mmap_anonymous.c Alloue 1 Gio avec une projection anonyme (MAP_ANONYMOUS) ; seule la page touchée reçoit un cadre de page (cours, chapitre "Mémoire virtuelle") Voir

Code source

src/memory_01.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* exit() and EXIT_SUCCESS */
#include <unistd.h>    /* getpagesize() */

/**
 * @file memory_01.c
 *
 * Demonstrates how to retrieve and display the system's memory page size.
 * Knowing the page size can be critical for performance tuning and memory
 * management tasks, as it influences how memory is allocated and managed
 * at the system level.
 *
 * Note: getpagesize() is an old BSD function, removed from POSIX; a portable
 * program uses sysconf(_SC_PAGESIZE) instead (see page_size.c).
 */

int main(void) {
    int pageSize = getpagesize();  /* Retrieve the system's page size */
    printf("Size of page on this system: %d bytes\n", pageSize);
    return EXIT_SUCCESS;
}
src/memory_02.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* exit() */
#include <unistd.h>    /* fork(), sleep() */
#include <sys/types.h> /* pid_t */
#include <time.h>      /* time() */
#include <signal.h>    /* signal handling */

/**
 * @file memory_02.c
 *
 * This program runs for approximately 4 minutes, during which its memory 
 * mapping can be inspected using system tools (e.g., `cat /proc/<PID>/maps` under Linux, `vmmap <PID>` under macOS). 
 * It is designed to aid in understanding the memory layout of a process. 
 * Useful for educational purposes to see how memory is allocated and modified
 * over time.
 */

void handle_signal(int sig) {
    /* Only async-signal-safe functions here: write() and _exit(). The handler
       ends the process at once, so the "flag only" rule of the course is not
       needed: nothing is left half-done in main(). */
    const char msg[] = "\nSignal received, exiting now...\n";
    (void) sig;
    write(STDOUT_FILENO, msg, sizeof(msg) - 1);
    _exit(EXIT_SUCCESS);
}

int main(void) {
    struct sigaction sa;
    time_t end = time(NULL) + 240;  /* Set the program to run for about 4 minutes */

    /* Setup the sigaction struct */
    sa.sa_handler = handle_signal;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;

    /* Set up SIGINT / Ctrl-C for graceful termination */
    if (sigaction(SIGINT, &sa, NULL) == -1) {
        perror("Error setting up sigaction");
        exit(EXIT_FAILURE);
    }

    printf("Process with PID %ld is running. Use `cat /proc/%ld/maps` to inspect memory layout.\n", (long) getpid(), (long) getpid());

    while (1) {
        if (time(NULL) >= end) {
            break;
        }
        sleep(1); /* Sleep to reduce CPU usage and allow time for manual inspection */
    }

    printf("Completed 4 minutes of runtime. Exiting.\n");

    return EXIT_SUCCESS;
}
src/memory_03.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* random(), exit() */
#include <unistd.h>    /* fork(), sleep() */
#include <sys/types.h> /* pid_t */
#include <signal.h>    /* signal handling */
#include <math.h>      /* sqrt() - link with -lm */

/**
 * @file memory_03.c
 *
 * This program continuously calculates the square root of random numbers,
 * demonstrating the use of the math library (libm) and allowing for the
 * inspection of its memory mapping. Use the following command to check 
 * memory usage:
 * \code{bash}
 * cat /proc/<PID>/maps     (Linux; on macOS: vmmap <PID>)
 * \endcode
 * 
 * Use Ctrl-C to gracefully exit the program.
 */

void handle_signal(int sig) {
    /* Only async-signal-safe functions here: write() and _exit() */
    const char msg[] = "\nSignal received, exiting now...\n";
    (void) sig;
    write(STDOUT_FILENO, msg, sizeof(msg) - 1);
    _exit(EXIT_SUCCESS);
}

int main(void) {
    struct sigaction sa;
    long number;
    double square_root;

    /* Setup the sigaction struct */
    sa.sa_handler = handle_signal;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;

    /* Set up SIGINT / Ctrl-C for graceful termination */
    if (sigaction(SIGINT, &sa, NULL) == -1) {
        perror("Error setting up sigaction");
        exit(EXIT_FAILURE);
    }

    printf("Process with PID %ld is calculating square roots. Check memory mapping with `cat /proc/%ld/maps`\n", (long) getpid(), (long) getpid());

    while (1) {
        number = random();
        square_root = sqrt(number);
        printf("Square root of %ld is %f\n", number, square_root);
        sleep(10); 
    }

    /* Unreachable: the process exits via signal */
}
src/memory_04.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* random(), exit(), malloc(), free() */
#include <unistd.h>    /* fork(), sleep() */
#include <signal.h>    /* sigaction */
#include <sys/types.h> /* pid_t */

/**
 * @file memory_04.c
 *
 * Demonstrates memory mapping of a process using a heap. Run the program and
 * verify its memory mapping using:
 * \code{bash}
 * cat /proc/<PID>/maps     (Linux; on macOS: vmmap <PID>)
 * \endcode
 * The process is stopped by Ctrl-C before free(): this is not a real leak, the
 * kernel takes back all the memory of a process when it ends. For a leak
 * detected by valgrind, see memory_05a.c.
 */

void handle_signal(int sig) {
    /* Only async-signal-safe functions here: write() and _exit(). The handler
       ends the process at once, so the "flag only" rule of the course is not
       needed: nothing is left half-done in main(). */
    const char msg[] = "\nSignal received, exiting now...\n";
    (void) sig;
    write(STDOUT_FILENO, msg, sizeof(msg) - 1);
    _exit(EXIT_SUCCESS);
}

int main(void) {
    struct sigaction sa;
    int *pointer;
    int value;

    /* Setup the sigaction struct to handle SIGINT (Ctrl-C) */
    sa.sa_handler = handle_signal;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;

    /* Apply the sigaction configuration */
    if (sigaction(SIGINT, &sa, NULL) == -1) {
        perror("Error setting up sigaction");
        exit(EXIT_FAILURE);
    }

    /* Allocate memory on the heap */
    pointer = (int *) malloc(sizeof(int));
    if (pointer == NULL) {
        perror("Failed to allocate memory");
        exit(EXIT_FAILURE);
    }

    printf("Process with PID %ld is running. Check memory mapping with `cat /proc/%ld/maps`\n", (long) getpid(), (long) getpid());

    /* Continuously write random values to allocated memory */
    while (1) {
        value = random();
        *pointer = value;
        printf("Stored value: %d at address %p\n", *pointer, (void *) pointer);
        sleep(5);
    }

    /* Code to free memory if reached, which it never is in this scenario */
    free(pointer);

    /* Unreachable code due to infinite loop and external termination via signals */
    return EXIT_SUCCESS;
}
src/memory_05a.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* exit(), malloc(), free() */
#include <unistd.h>    /* pause() */
#include <signal.h>    /* for sigaction */
#include <sys/types.h> /* pid_t */

/**
 * @file memory_05a.c
 *
 * This program allocates memory for an array of 10 integers and then pauses, 
 * creating an intentional memory leak for analysis with memory profiling tools
 * like Valgrind. Compile it with -g option and run the Valgrind program.
 */

void handle_signal(int sig) {
    /* Only async-signal-safe functions here: write() and _exit() */
    const char msg[] = "\nSignal received, exiting now...\n";
    (void) sig;
    write(STDOUT_FILENO, msg, sizeof(msg) - 1);
    _exit(EXIT_SUCCESS);
}

int main(void) {
    int *p;
    struct sigaction sa;

    /* Clear the sigaction structure */
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    sa.sa_handler = handle_signal;

    /* Set up sigaction for SIGINT */
    if (sigaction(SIGINT, &sa, NULL) == -1) {
        perror("Error setting up sigaction for SIGINT");
        exit(EXIT_FAILURE);
    }

    /* Allocate memory for 10 integers */
    p = (int *) malloc(10 * sizeof(int));
    if (!p) {
        perror("Failed to allocate memory");
        exit(EXIT_FAILURE);
    }

    /* Inform user about how to proceed */
    printf("Program paused. PID: %ld. Use Ctrl-C to exit.\n", (long) getpid());

    /* Pause the program, waiting for signal */
    pause();

    /* Never reached: the handler terminates the process with _exit(), so the
     * memory is never freed (compare with memory_05b.c) */
    free(p);

    return EXIT_SUCCESS;
}
src/memory_05b.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* exit(), malloc(), free() */
#include <unistd.h>    /* pause() */
#include <errno.h>
#include <signal.h>    /* sigaction */
#include <sys/types.h> /* pid_t */

/**
 * @file memory_05b.c
 *
 * This program allocates memory for an array of 10 integers, pauses (waiting 
 * for a signal), and then properly frees the allocated memory before exiting, 
 * demonstrating proper memory management.
 */

void handle_signal(int sig) {
    /* Only async-signal-safe functions here: the handler just returns, and
     * pause() then returns in main(), which frees the memory */
    const char msg[] = "\nSignal received. Cleaning up and exiting...\n";
    (void) sig;
    int saved_errno = errno; /* write() may change errno: restore it for main() */
    write(STDOUT_FILENO, msg, sizeof(msg) - 1);
    errno = saved_errno;
}

int main(void) {
    int *p;
    struct sigaction sa;

    /* Setup memory */
    p = (int *) malloc(10 * sizeof(int));
    if (!p) {
        perror("Failed to allocate memory");
        exit(EXIT_FAILURE);
    }

    /* Setup the sigaction structure */
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    sa.sa_handler = handle_signal;

    /* Register sigaction for SIGINT */
    if (sigaction(SIGINT, &sa, NULL) == -1) {
        perror("Error setting up sigaction");
        free(p);  /* Clean up before exit if sigaction setup fails */
        exit(EXIT_FAILURE);
    }

    printf("Process with PID %ld is paused. Press Ctrl-C to exit.\n", (long) getpid());
    pause();  /* Returns once the handler has run */

    /* Cleanup and exit */
    free(p);
    p = NULL;

    return EXIT_SUCCESS;
}
src/memory_06.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

/**
 * @file memory_06.c
 *
 * This program demonstrates the memory layout of a process in a Unix/Linux
 * environment by printing the addresses of various functions, global 
 * variables, and dynamically allocated memory, illustrating how different 
 * segments (text, data, heap, stack) are organized in memory. It is based
 * on the code by John Shapley Gray.
 *
 * Ref.: John Shapley Gray. "Interprocess Communications in Linux: The Nooks 
 * and Crannies". Prentice Hall. 2003.
 *
 * +------------------+
 * |  TEXT            | x     = main()
 * |                  |
 * |  instructions    | x     = pointer_function()
 * |  binary code     |
 * |                  |
 * +------------------+ x     = 'etext'
 * |  DATA            | x     = initialized globals
 * |  - initialized   |
 * |    variables     | x     = initialized static locals
 * |                  |
 * |                  | x     = 'edata'
 * |                  | x     = non-initialized static locals
 * |                  |
 * | ---------------  |
 * |  - non           | x     = 'end'
 * |  initialized     | x     = non-initialized globals
 * |  variables       |
 * |                  |
 * |                  |
 * | ---------------  |
 * |  - heap for      | x     = pointed by 'int_ptr1'
 * |    dynamic       | x       = pointed by 'int_ptr2'
 * |    allocation    |
 * |                  |
 * |                  |
 * +------------------+ x     = end of data segment(s)
 *          |
 *          |
 *          V
 *          .
 *          .
 *          .
 *          ^
 *          |
 *          |
 * +------------------+
 * |      STACK       |
 * |  - function      | x     = init local | Instruction pushed
 * |                  | x     = init local | for pointer_function()
 * |                  |
 * |  - local         | x     = loc        | Instruction pushed
 * |    variables     |                    | for main()
 * |                  |
 * +------------------+
 */

#define SHOW_ADDRESS(ID, I) printf("The id %s \t\t is at:%8lX\n", ID, (unsigned long int)&I);

/*
 * etext, edata and end are not variables of the program: they are symbols
 * defined by the linker (see man 3 end). Their ADDRESS is the end of the
 * text segment, of the initialized data and of the BSS. macOS does not
 * provide them, but offers get_etext(), get_edata() and get_end().
 */
#ifdef __APPLE__
#include <mach-o/getsect.h>
#define ADDR_ETEXT get_etext()
#define ADDR_EDATA get_edata()
#define ADDR_END   get_end()
#else
extern char etext, edata, end;
#define ADDR_ETEXT ((unsigned long int) &etext)
#define ADDR_EDATA ((unsigned long int) &edata)
#define ADDR_END   ((unsigned long int) &end)
#endif

char *g_pointer = "A string in C"; /* initialized global */
char g_buff[100];                  /* uninitialized global */

void pointer_function(int local_non_init) {
    int local_init;

    local_init = 3;

    SHOW_ADDRESS(" LocUninit (inside PtrFct) ", local_non_init)
    if (local_non_init > 0) {
        pointer_function(local_non_init - local_init);
    }
}

int main(int argc, char *argv[]) {
    int i = 3;                  /* local initialized --> stack segment */
    static long diff;           /* static local uninitialized --> BSS segment */
    static int stack_calls = 5; /* static local initialized --> data segment */

    int *int_ptr1 = (int *) malloc(10 * sizeof(int));  /* heap */
    if (!int_ptr1) {
        perror("Failed to allocate memory for int_ptr1");
        exit(EXIT_FAILURE);
    }
    int *int_ptr2 = (int *) malloc(10 * sizeof(int));  /* heap */
    if (!int_ptr2) {
        perror("Failed to allocate memory for int_ptr2");
        free(int_ptr1);  /* Clean up previous allocation */
        exit(EXIT_FAILURE);
    }

    snprintf(g_buff, sizeof(g_buff), " Layout of virtual memory \n ");

    if (write(1, g_buff, strlen(g_buff)) == -1) {
        perror("Error [write()]");
    }

    printf("Adr etext : %8lX \t\t Adr edata : %8lX \t\t Adr end : %8lX \n",
           ADDR_ETEXT, ADDR_EDATA, ADDR_END);

    printf(" Variable \t\t HEX_ADDR\n ");

    SHOW_ADDRESS(" main function", main);
    SHOW_ADDRESS(" pointer_function() ", pointer_function);
    printf("The id  etext  \t\t is at:%8lX\n", ADDR_ETEXT);
    diff = (long) ((unsigned long int) &pointer_function - (unsigned long int) &main);
    printf(" pointer_function() is  %ld bytes above main\n", diff);


    SHOW_ADDRESS(" Global pointer ", g_pointer);
    diff = (long) ((unsigned long int) &g_pointer - (unsigned long int) &pointer_function);
    printf(" g_pointer is %ld bytes above pointer_function()\n", diff);

    SHOW_ADDRESS(" Global Buff", g_buff);
    printf(" int_ptr1 %8lX\n", (unsigned long int) int_ptr1);
    printf(" int_ptr2 %8lX\n", (unsigned long int) int_ptr2);
    SHOW_ADDRESS(" diff ", diff);
    SHOW_ADDRESS(" stack calls", stack_calls);
    printf("The id  edata  \t\t is at:%8lX\n", ADDR_EDATA);
    printf("The id  end  \t\t is at:%8lX\n", ADDR_END);
    SHOW_ADDRESS(" argc ", argc);
    SHOW_ADDRESS(" argv ", argv);
    SHOW_ADDRESS(" i ", i);
    pointer_function(stack_calls);

    return EXIT_SUCCESS;
}
src/memory_07.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>    /* uintptr_t */
#include <sys/types.h>
#include <unistd.h>

/**
 * @file memory_07.c
 *
 * This program demonstrates the memory layout of a process by printing the
 * addresses of the main function, another function, a local variable (stack),
 * and a dynamically allocated memory block (heap).
 */

void print_stack_location(void) {
    int stack_variable;
    printf("Location of stack variable inside function: %p\n", (void *)&stack_variable);
}

int main(void) {
    void *heap_memory;

    /* ISO C forbids converting a function pointer directly to void *:
     * go through an integer type (uintptr_t) */
    printf("Location of main() function code: %p\n", (void *) (uintptr_t) main);
    printf("Location of print_stack_location() function code: %p\n", (void *) (uintptr_t) print_stack_location);

    print_stack_location(); /* Function call to demonstrate stack location */

    heap_memory = malloc(100000000UL); /* 100 MB */
    if (heap_memory == NULL) {
        fprintf(stderr, "Failed to allocate memory.\n");
        return EXIT_FAILURE;
    }

    printf("Location of heap allocated memory: %p\n", heap_memory);

    free(heap_memory); /* Free the allocated memory */
    return EXIT_SUCCESS;
}
src/mmap1.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* exit() */
#include <unistd.h>    /* write(), close() */
#include <fcntl.h>     /* open() opening flags and file modes */
#include <sys/mman.h>  /* mmap() */
#include <sys/stat.h>  /* stat() */
#include <sys/types.h>
#include <ctype.h>     /* isalpha(), isspace() */
#include <assert.h>

/**
 * @file mmap1.c
 *
 * This program demonstrates memory mapping of a file using mmap(). It maps the
 * contents of a specified file into memory, writes the content to the terminal,
 * processes the data, and then unmaps the memory.
 */

#define TERMINAL STDOUT_FILENO

/**
 * Get the size of an open file using fstat(): open() first, then fstat() on
 * the descriptor, so that the size is that of the file actually opened.
 */
long get_file_size(int fd) {
    struct stat st;
    if (fstat(fd, &st) == -1) {
        perror("Error using fstat()");
        exit(EXIT_FAILURE);
    }
    return st.st_size;
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <file>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int fd;
    long file_size;
    char *projection;

    fd = open(argv[1], O_RDONLY);
    if (fd == -1) {
        perror("Error opening file");
        exit(EXIT_FAILURE);
    }

    file_size = get_file_size(fd);

    projection = mmap(NULL, file_size, PROT_READ, MAP_SHARED, fd, 0);
    if (projection == MAP_FAILED) {
        perror("Error using mmap()");
        close(fd);
        exit(EXIT_FAILURE);
    }

    if (write(TERMINAL, projection, file_size) == -1) {
        perror("Error using write()");
        munmap(projection, file_size);
        close(fd);
        exit(EXIT_FAILURE);
    }

    /* The projection is read like an array: here, only the characters that
       are neither letters nor spaces (digits, punctuation) are displayed */
    for (long i = 0; i < file_size; i++) {
        if (i % 80 == 79) {
            putchar('\n');
        } else if (!isalpha((unsigned char) projection[i]) &&
                   !isspace((unsigned char) projection[i])) {
            putchar(projection[i]);
        }
    }

    munmap(projection, file_size);
    close(fd);

    return EXIT_SUCCESS;
}
src/mmap2.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdio.h>     /* printf() */
#include <stdlib.h>    /* exit() */
#include <unistd.h>    /* lseek(), write(), close() */
#include <fcntl.h>     /* open() opening flags and file modes */
#include <sys/mman.h>  /* mmap() */
#include <sys/stat.h>  /* stat() */
#include <sys/types.h>
#include <string.h>    /* memcpy() */

/**
 * @file mmap2.c
 *
 * This program replicates the functionality of the cp command by using memory
 * mapping. It maps the contents of a source file into memory, then maps a 
 * destination file into memory, and performs a memory copy from the source to
 * the destination.
 */

/**
 * Get the size of the file by its filename using stat().
 */
long get_file_size(const char *filename) {
    struct stat st;

    if (stat(filename, &st) == -1) {
        perror("Error using stat()");
        exit(EXIT_FAILURE);
    }

    return (long) st.st_size;
}

int main(int argc, char *argv[]) {
    int fdin;
    int fdout;
    char *src;
    char *dst;
    long file_size;

    if (argc != 3) {
        printf("Usage: mmap2 <src> <dest>\n");
        exit(EXIT_FAILURE);
    }

    file_size = get_file_size(argv[1]);

    if (file_size == 0) {  /* an empty file cannot be projected (EINVAL) */
        fprintf(stderr, "%s: empty file\n", argv[1]);
        exit(EXIT_FAILURE);
    }

    fdin = open(argv[1], O_RDONLY);
    if (fdin == -1) {
        perror("Error opening source file");
        exit(EXIT_FAILURE);
    }
    fdout = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, 0644);
    if (fdout == -1) {
        perror("Error opening destination file");
        exit(EXIT_FAILURE);
    }

    /* Give the destination file its size: go to the last byte and write
     * one char there (ftruncate(fdout, file_size) would do the same) */
    if (lseek(fdout, file_size - 1, SEEK_SET) == -1 ||
        write(fdout, "", 1) == -1) {
        perror("Error sizing destination file");
        exit(EXIT_FAILURE);
    }

    /* Project the input file in memory */
    src = mmap(NULL, file_size, PROT_READ, MAP_SHARED, fdin, 0);
    if (src == MAP_FAILED) {
        perror("Error using mmap() on source");
        exit(EXIT_FAILURE);
    }

    /* Same for the output one */
    dst = mmap(NULL, file_size, PROT_READ | PROT_WRITE, MAP_SHARED, fdout, 0);
    if (dst == MAP_FAILED) {
        perror("Error using mmap() on destination");
        exit(EXIT_FAILURE);
    }

    /* Performs a memory copy from src to dst */
    memcpy(dst, src, file_size);

    munmap(src, file_size);
    munmap(dst, file_size);   /* the copy is carried over to the file */
    close(fdin);
    close(fdout);

    return EXIT_SUCCESS;
}
src/mmap_anonymous.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _DEFAULT_SOURCE 1  /* MAP_ANONYMOUS with glibc */
#define _DARWIN_C_SOURCE 1 /* MAP_ANONYMOUS with macOS */
#include <stdio.h>     /* printf(), perror() */
#include <stdlib.h>    /* exit() */
#include <sys/mman.h>  /* mmap(), munmap() */

/**
 * @file mmap_anonymous.c
 * @brief Allocates 1 GiB with an anonymous projection (MAP_ANONYMOUS).
 *
 * Lecture: chapter os-09a "Mémoire virtuelle" ("Projection anonyme").
 *
 * The area is linked to no file and is filled with zeros. Only the pages
 * actually touched receive a physical frame: here, only the first one.
 *
 * Key points:
 *   - works like a dynamic allocation, without fragmenting the heap:
 *     munmap() returns the whole area to the system;
 *   - MAP_ANONYMOUS is standard since POSIX 2024; before: MAP_ANON (BSD)
 *     or a projection of /dev/zero;
 *   - with MAP_SHARED | MAP_ANONYMOUS, the area is shared with the
 *     children created by fork().
 *
 * \code{.bash}
 *   $ ./mmap_anonymous
 *   t[0] = 42, t[1] = 0
 * \endcode
 */

int main(void) {
    size_t taille = 1UL << 30;              /* 1 GiB */
    int *t = mmap(NULL, taille, PROT_READ | PROT_WRITE,
                  MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if (t == MAP_FAILED) { perror("mmap"); exit(EXIT_FAILURE); }

    t[0] = 42;     /* only this page receives a frame */
    printf("t[0] = %d, t[1] = %d\n", t[0], t[1]);

    munmap(t, taille);  /* returned to the system, without a hole */

    return EXIT_SUCCESS;
}
src/mmap_toupper.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>     /* perror(), fprintf() */
#include <stdlib.h>    /* exit() */
#include <ctype.h>     /* toupper() */
#include <fcntl.h>     /* open() */
#include <unistd.h>    /* close() */
#include <sys/mman.h>  /* mmap(), munmap() */
#include <sys/stat.h>  /* fstat() */
#include <sys/types.h> /* off_t */

/**
 * @file mmap_toupper.c
 * @brief Modifies a file in place through a shared projection
 * (MAP_SHARED): converts it to upper case.
 *
 * Lecture: chapter os-09a "Mémoire virtuelle" ("Exemple - modifier un
 * fichier en place").
 *
 * Key points:
 *   - the file is opened in O_RDWR: with MAP_SHARED, PROT_WRITE requires
 *     it (otherwise mmap() fails with EACCES);
 *   - the modifications of the memory area are carried over to the file;
 *   - mmap() returns MAP_FAILED (not NULL) on failure;
 *   - an empty file cannot be projected (length 0 gives EINVAL).
 *
 * \code{.bash}
 *   $ echo bonjour > notes.txt
 *   $ ./mmap_toupper notes.txt
 *   $ cat notes.txt
 *   BONJOUR
 * \endcode
 */

int main(int argc, char *argv[]) {
    const char *nom = (argc > 1) ? argv[1] : "notes.txt";

    int fd = open(nom, O_RDWR);
    if (fd == -1) { perror("open"); exit(EXIT_FAILURE); }

    struct stat st;
    if (fstat(fd, &st) == -1) { perror("fstat"); exit(EXIT_FAILURE); }
    if (st.st_size == 0) {
        fprintf(stderr, "%s : fichier vide\n", nom);
        exit(EXIT_FAILURE);
    }

    char *p = mmap(NULL, st.st_size,
                   PROT_READ | PROT_WRITE,
                   MAP_SHARED, fd, 0);
    if (p == MAP_FAILED) { perror("mmap"); exit(EXIT_FAILURE); }

    for (off_t i = 0; i < st.st_size; i++) {
        p[i] = toupper((unsigned char) p[i]);
    }

    munmap(p, st.st_size);   /* the file is modified */
    close(fd);

    return EXIT_SUCCESS;
}
src/page_size.c

Voir sur GitHub

/*
 * Unix System Programming Examples / Exemplier de programmation système Unix
 *
 * Copyright (C) 1995-2026 Alain Lebret
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>     /* printf(), perror() */
#include <stdlib.h>    /* EXIT_SUCCESS, EXIT_FAILURE */
#include <unistd.h>    /* sysconf() */

/**
 * @file page_size.c
 * @brief Displays the page size using the POSIX function sysconf().
 *
 * Lecture: chapter os-09a "Mémoire virtuelle" ("Connaître la taille des
 * pages").
 *
 * POSIX variant of memory_01.c, which uses getpagesize() (removed from
 * POSIX). A portable program never assumes 4096: it asks the system.
 *
 * \code{.bash}
 *   $ ./page_size             # Linux, x86-64
 *   taille de page : 4096 octets
 *   $ ./page_size             # macOS, Apple Silicon
 *   taille de page : 16384 octets
 * \endcode
 */

int main(void) {
    long taille = sysconf(_SC_PAGESIZE);    /* POSIX */
    if (taille == -1) {
        perror("sysconf");
        return EXIT_FAILURE;
    }
    printf("taille de page : %ld octets\n", taille);
    return EXIT_SUCCESS;
}