利用C语言"位域"的特殊性来对数组进行边界检查
2017-12-06 10:31
393 查看
1.序
数组越界时常有发生,如果我们能够让编译器提醒我们犯错那是最好。2.例子
#include <stdio.h> #include <stdlib.h> #define ARRAY_CARDINALITY(Array) (sizeof(Array) / sizeof(*(Array))) #undef YIN_VERIFY #define YIN_VERIFY(name,cond) static char name ## dummy [sizeof(struct { unsigned char dummy:((cond)?1:-1);})] __attribute__ ((unused)) int yin_util_str2enum(const char *const*types, unsigned int ntypes, const char *type); const char *yin_util_enum2str(const char *const*types, unsigned int ntypes, int type); #define YIN_ENUM_IMPL(name, lastVal, ...) \ static const char *const name ## TypeList[] = { __VA_ARGS__ }; \ YIN_VERIFY(name,(ARRAY_CARDINALITY(name ## TypeList) == lastVal)); \ const char *name ## TypeToString(int type) { \ return yin_util_enum2str(name ## TypeList, \ ARRAY_CARDINALITY(name ## TypeList), \ type); \ } \ int name ## TypeFromString(const char *type) { \ return yin_util_str2enum(name ## TypeList, \ ARRAY_CARDINALITY(name ## TypeList), \ type); \ } #define YIN_ENUM_DECL(name) \ const char *name ## TypeToString(int type); \ int name ## TypeFromString(const char*type); /* Exported functions ------------------------------------------------------- */ int yin_util_str2enum(const char *const*types, unsigned int ntypes, const char *type) { size_t i; if (!type) return -1; for (i = 0; i < ntypes; i++){ if (0 == strcmp(types[i], type)) return i; } return -1; } const char * yin_util_enum2str(const char *const*types, unsigned int ntypes, int type) { if (type < 0 || type >= ntypes) return NULL; return types[type]; } // enum { EUNKOW, ENAME, EAGE, EBUTT }; YIN_ENUM_IMPL(student,EBUTT,"uknow","name") int main(int argc, char *argv[]) { return 0; }
执行报错:
enum2str.c:7:72: error: negative width in bit-field 'dummy' #define YIN_VERIFY(name,cond) static char name ## dummy [sizeof(struct { unsigned char dummy:((cond)?1:-1);})] __attribute__ ((unused)) ^ enum2str.c:20:2: note: in expansion of macro 'YIN_VERIFY' YIN_VERIFY(name,(ARRAY_CARDINALITY(name ## TypeList) == lastVal)); \ ^ enum2str.c:72:1: note: in expansion of macro 'YIN_ENUM_IMPL' YIN_ENUM_IMPL(student,EBUTT,"uknow","name") ^
将 YIN_ENUM_IMPL(student,EBUTT,”uknow”,”name”) 改为 YIN_ENUM_IMPL(student,EBUTT,”uknow”,”name”,”age”) 错误解决。
相关文章推荐
- 项目经验之谈 —— 利用编译器及C语言特性<位域>进行内存边界检测
- c语言:为什么不进行下标检查,总结下指针和数组
- 利用c语言来进行简单的模拟ATM机
- 利用数组进行冒泡法排序举例
- 今天学习时突然联想到这样一个有趣但无用的问题:利用C语言(不能是其他语言)求两个整数的较大/小值-----要求不用if、三目?、switch、循环、数组、加减乘除求余、位运算符以及任何库函数
- 【C语言】将一个数组进行初始化、清空、逆序、显示。
- c语言:将数组A中的内容和数组B中的内容进行交换。(数组一样大)
- 利用冒泡排序对数组进行排序
- Vb.net 利用数组进行组合查询
- 利用指针对数组&句子进行逆序
- 利用"$((...))"进行简单的数值运算
- 利用单元测试在每个层上对PHP代码进行检查
- 程序员之---C语言细节12(指针和数组细节,"//"的可移植性说明)
- 利用函数指针对数组进行排序
- Linux在Terminal中利用C语言进行清屏
- 7068-2.Python数据分析:利用数组进行数据处理
- C语言通讯录管理系统 利用fwrite和fread进行文件存取
- 利用函数指针对数组进行排序
- 桶排序:利用数组下标进行排序
- C/C++利用位运算来进行函数参数检查