在Linux中没有像Windows API提供的IsBadWritePtr类似的函数或者系统调用。不过你可以自己实现类似的功能,下面的代码实现了函数IsReadBadPtr, IsWriteBadPtr的实现类似。 大致原理是在linux下非法指针访问产生SIGSEGV, 并且会产生core dump, 你在测试指针之前设置自己的SIGSEGV信号处理函数就 可以不产生core dump。
参考:http://bbs.csdn.net/topics/80398644
http://zhangyafeikimi.iteye.com/blog/248822
#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;
}
文章的脚注信息由WordPress的wp-posturl插件自动生成
微信扫一扫,打赏作者吧~![[整理][转载]win下网卡抓包发包库Npcap使用](http://www.jyguagua.com/wp-content/themes/begin/timthumb.php?src=http://www.jyguagua.com/wp-content/uploads/2023/08/demo_1-1024x711.jpg&w=280&h=210&zc=1)
![[转载]基础数据char,int,double,string是线程安全的吗?](http://www.jyguagua.com/wp-content/themes/begin/img/random/6.jpg)
![[已解决]nc命令报错 close: Bad file descriptor](http://www.jyguagua.com/wp-content/themes/begin/timthumb.php?src=http://www.jyguagua.com/wp-content/uploads/2022/03/Snipaste_2022-03-18_20-16-48.png&w=280&h=210&zc=1)
![[整理]how to run flask with pyqt5](http://www.jyguagua.com/wp-content/themes/begin/timthumb.php?src=http://www.jyguagua.com/wp-content/uploads/2021/03/pyqt_flask.png&w=280&h=210&zc=1)