Skip to content

Instantly share code, notes, and snippets.

@the6p4c
Created September 27, 2019 11:28
Show Gist options
  • Select an option

  • Save the6p4c/72e69eda653d4a75c86b9939710dbd5b to your computer and use it in GitHub Desktop.

Select an option

Save the6p4c/72e69eda653d4a75c86b9939710dbd5b to your computer and use it in GitHub Desktop.

Revisions

  1. the6p4c created this gist Sep 27, 2019.
    33 changes: 33 additions & 0 deletions bug.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    // 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);
    free(y);

    shmdt(x);

    shmctl(shmid, IPC_RMID, NULL);
    }