Skip to content

Instantly share code, notes, and snippets.

@dreadpiratepj
Created May 15, 2009 17:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dreadpiratepj/112334 to your computer and use it in GitHub Desktop.
Save dreadpiratepj/112334 to your computer and use it in GitHub Desktop.
void *newScratchArea(int sizeInBytes) {
/*
Create a temporary file. This file will be automatically
destroyed by the system when our process exits.
*/
FILE *f = tmpfile();
if (f) {
/* Get the file descriptor from the FILE pointer. */
int fd = fileno(f);
if (fd >= 0) {
/* Resize (via ftruncate()) to the size we want. */
if (0 == ftruncate(fd, sizeInBytes)) {
/* Map the file into an unused area of the process's address space. */
void *result = mmap(
NULL, /* No preferred address. */
sizeInBytes, /* Size of mapped space. */
PROT_READ | PROT_WRITE, /* Read/write access. */
MAP_FILE | MAP_SHARED, /* Map from file (default) and map as shared (see above.) */
fd, /* The file descriptor. */
0 /* Offset from start of file. */
);
if (result)
return result;
}
}
/* failure */
fclose(f);
}
return NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment