确保 printf(3S)、sprintf(3S)、scanf(3S) 和 sscanf(3S) 的格式字符串可以容纳 long 或指针参数。对于指针参数,格式字符串中提供的转换操作应为 %p,以便能在 32 位和 64 位编译环境中运行。请看以下示例:
char *buf; struct dev_info *devi; ... (void) sprintf(buf, "di%x", (void *)devi); % warning: function argument (number) type inconsistent with format sprintf (arg 3) void *: (format) int
修改后的版本为:
char *buf; struct dev_info *devi; ... (void) sprintf(buf, ”di%p", (void *)devi);
对于 long 参数,long 长度规范 l 应前置于格式字符串中的转换操作字符前面。另外,还要检查以确保 buf 指向的存储器足以包含 16 个数字。
size_t nbytes; u_long align, addr, raddr, alloc; printf("kalloca:%d%%%d from heap got%x.%x returns%x\n", nbytes, align, (int)raddr, (int)(raddr + alloc), (int)addr); % warning: cast of 64-bit integer to 32-bit integer warning: cast of 64-bit integer to 32-bit integer warning: cast of 64-bit integer to 32-bit integer
修改后的版本为:
size_t nbytes; u_long align, addr, raddr, alloc; printf("kalloca:%lu%%%lu from heap got%lx.%lx returns%lx\n", nbytes, align, raddr, raddr + alloc, addr);