malloc导致分段错误

malloc导致分段错误

本文介绍了在mprotect之后,malloc导致分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用mprotect()保护内存区域后,我第一次调用malloc()时遇到了段错误.这是一个代码片段,它为保护分配内存:

I'm getting a segmentation fault the first time I call malloc() after I protect a memory region with mprotect(). This is a code sniplet that does the memory allocation the the 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");
        }
}

我想使用mprotect避免任何东西写入我的数组(它们是预先计算的正弦/余弦值).这是一个愚蠢的主意吗?

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

推荐答案

mprotect 只能以页面为单位.在这种情况下,您可以正确地将代码块的开头与页面边界对齐,但是 要做的是确保分配范围扩展到您要转到的最后一页的末尾在其中使用.

mprotect can only work in units of pages, as you probably already know. In this case, you're correctly aligning the start of your block to a page boundary, but what you're not doing is ensuring that your allocation extends to the end of the last page you're going to use in it.

这意味着您的 mprotect 正在保护分配结束后(一直到该页面末尾)的数据,该空间是下一个 malloc 调用所假定的空间它可以写入.

This means that your mprotect is protecting data past the end of your allocation (right to the end of that page), which is space that the next malloc call assumes it can write to.

最简单的解决方法是将 malloc 调用中的 PAGE_SIZE-1 更改为 PAGE_SIZE * 2 .

The easiest fix is to change the PAGE_SIZE - 1 in the malloc call to PAGE_SIZE * 2.

这篇关于在mprotect之后,malloc导致分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 06:59