《C语言接口与实现》学习笔记系列之一

《C语言接口与实现》第二章课后练习题中有一题是这样的

It's often possible to detect certain invalid pointers.For example, a nonnull pointer is invalid if it sepcifies an address outside the client's

address space, and pointers are often subject to alignment restrictions; for example, on some systems a pointer to a double must be a

multiple of eight. Devise a system-specific macro isBadPtr(p) that is one when p is an invalid pointer so that occurrences of assert(ptr)

can be replaces with assertions like assert(!isBadPtr(p)).

 

思路如下:

1 要判断指针是否合法关键是需要知道p指向的类型是按几的倍数对齐的,假设p指向的类型为T,既需要知道sizeof(T)。

2 根据指针支持++运算符指向下一个元素得到启发,sizeof(T) = (unsigned int)(p+1)-(unsigned int)p

3 判断p是否合法只需要验证p指向的地址是否按sizeof(T)字节对齐即可。

SO 得到如下宏定义:

#define isBadPtr(p)  ((unsigned int)(p)%((unsigned int)(p+1)-(unsigned int)(p))) != 0)

在C语言中经常使用void*来支持传递各种不同类型数据,这样就需要转换两次,如果两次类型不同就可能出现bad pointer。

目前在阅读的代码中还没有见到使用类似的宏判断指针的合法性的,所以感觉实用性不佳。

posted @ 2012-11-19 23:32  BlueCode  阅读(669)  评论(0)    收藏  举报