Skip to content

Instantly share code, notes, and snippets.

@weissi
Created November 11, 2014 16:46
Show Gist options
  • Save weissi/50930f3898bdc18c63e0 to your computer and use it in GitHub Desktop.
Save weissi/50930f3898bdc18c63e0 to your computer and use it in GitHub Desktop.
Program to leak shared memory on OS X
#include <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
int main()
{
int err = 0;
const size_t size = 100 * 1024 * 1024;
char *shm_name = NULL;
asprintf(&shm_name, "shm-foo-%d", getpid());
printf("shm name: '%s'\n", shm_name);
int fd = shm_open(shm_name, O_CREAT | O_RDWR, 0644);
if (fd < 0) {
perror("shm_open");
return 1;
}
err = shm_unlink(shm_name);
if (err) {
perror("shm_unlink");
return 1;
}
err = ftruncate(fd, size);
if (err) {
perror("ftruncate");
return 1;
}
char *mem = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, fd, 0);
if (MAP_FAILED == mem) {
perror("mmap");
close(fd);
return 1;
}
if ('A' == *mem) {
printf("FILLED\n");
} else {
printf("not filled (%c)\n", *mem);
}
memset(mem, 'A', size);
pid_t pid = fork();
if (pid > 0) {
/* parent */
} else if (0 == pid) {
/* child */
sleep(10);
err = close(fd);
if (err) {
perror("close child");
return 1;
}
err = munmap(mem, size);
if (err) {
perror("munmap child");
return 1;
}
printf("should be freed now\n");
return 0;
} else {
perror("fork");
return 1;
}
err = close(fd);
if (err) {
perror("close");
return 1;
}
err = munmap(mem, size);
if (err) {
perror("munmap");
close(fd);
return 1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment