[ create a new paste ] login | about

Link: http://codepad.org/Ysn2roYC    [ raw code | output | fork ]

C, pasted on Aug 9:
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

/**
 ** A quasi-implementation of malloc(), which allocates 2 additional words, one
 ** before the memory segment of the requested size, one after. It protects
 ** those words against reading/writing, so accessing them raises a SIGSEGV.
 ** \param size length of the memory segment to be allocated for reading/writing
 ** \returns a pointer to the allocated memory, NULL on failure
 ** \warning Needs to be freed by free_bounded(), not the regular free()
 **/
static void* malloc_bounded(size_t size) {
    int fd = open("/dev/zero", O_RDWR);
    size_t *stp = NULL;
    
    if (fd != -1) {
        size   +=  2 * sizeof(size_t);  //+boundry words
        stp    =   mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
        if (stp != MAP_FAILED) {
            *stp   =   size;                //write metadata to the first word
            //seal both ends:
            mprotect(stp,                                sizeof(size_t), PROT_NONE);
            mprotect((((char*)stp)+size)-sizeof(size_t), sizeof(size_t), PROT_NONE);
            ++stp;
        }
        else
            stp = NULL;
        close(fd);
    }
    return (void *)stp;
}

int main()
{
    char *s = malloc_bounded(100);
    s[98] = '\0';
    return 0;
}


Output:
1
Segmentation fault


Create a new paste based on this one


Comments: