2025/02/18

C Check that the pointer is in range of the memory.

It's hard to say. It's important to protect yourself.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Function to check if a pointer is within the process's mapped memory regions
int is_pointer_in_memory_range(void *ptr) {
    FILE *fp = fopen("/proc/self/maps", "r");
    if (!fp) {
        perror("fopen");
        return 0;
    }

    char line[256];
    uintptr_t addr = (uintptr_t)ptr;
    uintptr_t start, end;
    while (fgets(line, sizeof(line), fp)) {
        if (sscanf(line, "%lx-%lx", &start, &end) == 2) {
            if (addr >= start && addr < end) {
                fclose(fp);
                return 1; // Pointer is in a valid range
            }
        }
    }

    fclose(fp);
    return 0; // Pointer is not in the mapped memory range
}