Malloc results in segmentation error after mprotect

I get a segmentation error on the first call to malloc () after protecting the memory area with mprotect (). This is a sniplet of code that allocates memory for protection:

#define PAGESIZE 4096
void* paalloc(int size){   // Allocates and aligns memory
        int type_size =  sizeof(double);
        void* p;
        p = malloc(type_size*size+PAGESIZE-1);
        p = (void*)(((long) p + PAGESIZE-1) & ~(PAGESIZE-1));
        return p;
}
void aprotect(int size, void* array){  // Protects memory after values are set
        int type_size = sizeof(double);
        if (mprotect(array, type_size*size, PROT_READ)) {
                perror("Couldn't mprotect");
        }
}

I want to use mprotect to avoid writing to my arrays (which are pre-calculated sine / cosine values). Is this a stupid idea?

+3
source share
3 answers

mprotect , , , . , , , - , , .

, mprotect ( ), , malloc , .

- PAGE_SIZE - 1 malloc PAGE_SIZE * 2.

+7

mmap , mprotect . , . () . .

+1

caf , .

, mprotect(): lookup.c ( ), double get_sine(int index);. , lookup.c get_sine(), .

, mprotect():

POSIX , mprotect() , mmap (2)

(-, Linux. ?)

0
source

Source: https://habr.com/ru/post/1722101/


All Articles