在我使用mprotect()保護內存區域後,第一次調用malloc()時出現了分段錯誤。這是一個代碼sniplet,做內存分配的保護:malloc導致mprotect出現分段錯誤
#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");
}
}
我想用mprotect的避免任何寫入我的數組(這是預先計算正弦/餘弦值)。這是一個愚蠢的想法嗎?
請同時添加類型cast(void *)mallac .... – Vijay 2009-11-06 12:59:56
@john:您不需要轉換 – Wernsey 2009-11-06 13:03:20
沒有足夠的關聯來編輯帖子,但是那些發現這個問題的人可能也會對這:http://stackoverflow.com/questions/1686464/alternatives-to-mprotect咖啡的關於頁面對齊的答案已經死了,似乎今天是一個熱門話題:) – 2009-11-06 13:32:32