请问:linux下有没有类似windows下的IsbadWritePtr的函数啊?

一个大好人 2006-03-16 10:07:40
就是判断一段内存是否可读可写的函数
...全文
306 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
alaiyeshi 2006-03-16
  • 打赏
  • 举报
回复
不知道
帮你顶
顺便学习
x86 2006-03-16
  • 打赏
  • 举报
回复
没有类似的函数或者系统调用。不过你可以自己实现类似的功能,下面的代码实现了函数IsReadBadPtr, IsWriteBadPtr的实现类似。大致原理是在linux下非法指针访问产生SIGSEGV, 并且会产生core dump, 你在测试指针之前设置自己的SIGSEGV信号处理函数就可以不产生core dump。

#include <setjmp.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>

/*
***************************
* Global Variables
***************************
*/
static volatile sig_atomic_t segv_flag;
static jmp_buf jmp_env;

/*
********************************************
* Pre: none
* Post: restore the original process state
* and return 1 to setjmp
********************************************
*/
static void segv_handler( int dummy )
{
segv_flag = 1;
longjmp( jmp_env , 1);
}

/*
********************************************
* Pre: A pointer and it's length
* Post: Return true is the pointer is bad
* or false if otherwise
********************************************
*/

int IsReadBadPtr(void * ptr_buffer, unsigned long buffer_size)
{
struct sigaction oldaction, newaction;
volatile char dummy;
char *ptr = (char *)ptr_buffer;

if ( !buffer_size )
return 0;

/* storing the old signal environment and trapping SIGSEGV */
newaction.sa_handler = segv_handler;
newaction.sa_flags = 0;
sigemptyset( &newaction.sa_mask);

sigaction( SIGSEGV, &newaction, &oldaction);

segv_flag = 0;

/* Storing the process state so if any failure happens
we can restore it to the original state */
if ( setjmp(jmp_env) == 0 )
{
/* testing the pointer: only the first and the end are needed here since any failure to any of this would indicate there would an error on the entire range */
dummy = ptr[0];
dummy = ptr[buffer_size-1];
}

/* restoring the original signal environment */
sigaction(SIGSEGV, &oldaction, NULL);

return segv_flag;
}

int main()
{
char *testptr,c; // testptr[10],结果将是Ok read Ptr

if ( IsReadBadPtr(testptr, 10))
printf(" Bad read Ptr\n");
else
printf(" Ok read Ptr\n");
fflush(stdout);
return 0;
}

23,116

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧