Skip to content

Instantly share code, notes, and snippets.

@HaskellZhangSong
Created August 28, 2025 07:43
Show Gist options
  • Select an option

  • Save HaskellZhangSong/df9743705162f667eb966ce65a5fda43 to your computer and use it in GitHub Desktop.

Select an option

Save HaskellZhangSong/df9743705162f667eb966ce65a5fda43 to your computer and use it in GitHub Desktop.
allocate memory with mmap
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include <errno.h>
#include <stdint.h>
// Size of allocation (1MB by default)
#define ALLOC_SIZE (1024 * 1024)
int main() {
// Target address: 256MB (0x10000000)
void* target_addr = (void*)0x10000000;
// Get system page size
long page_size = sysconf(_SC_PAGESIZE);
printf("System page size: %ld bytes\n", page_size);
printf("Attempting to allocate %d bytes at address %p (256MB)\n",
ALLOC_SIZE, target_addr);
// Try to map memory at the specified address
void* result = mmap(
target_addr, // Requested address
ALLOC_SIZE, // Size of mapping
PROT_READ | PROT_WRITE, // Memory protection
MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, // Flags
-1, // File descriptor (not used for anonymous)
0 // Offset (not used for anonymous)
);
if (result == MAP_FAILED) {
printf("Failed to allocate at 256MB: %s\n", strerror(errno));
return 1;
}
printf("Successfully allocated memory at %p\n", result);
// Write to the memory to ensure it's accessible
memset(result, 0xAB, ALLOC_SIZE);
// Read back first byte to verify
unsigned char* check = (unsigned char*)result;
printf("Memory check: First byte = 0x%02X (expected 0xAB)\n", *check);
// Keep the mapping active until user input
printf("\nPress Enter to unmap and exit...\n");
getchar();
// Unmap the memory
munmap(result, ALLOC_SIZE);
printf("Unmapped memory at 256MB\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment