Skip to content

Instantly share code, notes, and snippets.

@The6P4C The6P4C/bug.c
Created Sep 27, 2019

What would you like to do?
// Build with gcc -o bug bug.c
// Prints non-NULL address of y when executed outside of valgrind, and a NULL
// (rendered as "(nil)" by printf) when executed inside valgrind.
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int shmid = shmget(IPC_PRIVATE, 1024 * 1024 * 2, IPC_CREAT | 0666);
if (shmid < 0) {
fprintf(stderr, "Failed to create SHM segment\n");
return 1;
char *x = shmat(shmid, NULL, 0);
if (x == (void *) -1) {
fprintf(stderr, "Failed to attach to SHM segment\n");
return 1;
char *y = malloc(1);
printf("y = %p\n", y);
shmctl(shmid, IPC_RMID, NULL);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.