(GCC) Address warnings——Addresses always evaluate as true

这篇博客讨论了GNU Compiler Collection (GCC) 4.6.3 中关于内存地址的警告,特别是当地址总是评估为真、比较指针与字符串以及比较函数地址与0或NULL时发出的警告。文章通过示例展示了这些问题并提供了相关的警告信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2014-02-27 wcdj

Address warnings

The GNU compiler collection (GCC) 4.6.3 warns about suspicious uses of memory addresses. The memoryaddress [-Waddress] warning is enabledby specifying the -Wall compiler option.

Addresses always evaluate as true

Problem: I received the following warning: the address of 'ThisSubCommand' will always evaluate as ‘true’ [-Waddress]

Solution: The compiler issues a warning when a pointeraddress by itself is compared in an if statement. You mighthave wanted to test whether the string is a null string; that is,to test if the first element of the string is ‘\0’. In thiscase, you must check the contents of the first element. Change thecode to use an if statement to compare the first elementof the structure, or use the memcmp function to dothe comparison. For example, fix this code:
if (ThisSubCommand)    {
Corrected code:
if (ThisSubCommand[0] != '\0')

Comparing a pointer to a string

Problem: I received the following warning: comparison withstring literal results in unspecified behaviour [-Waddress]

Solution: The compiler issues a warning when a pointeris compared to a string. Change the code to use the memcmp function. Forexample, fix this code:
char * msg_prefix = "APGM";
⋮
if ( (msg_prefix == "APGM")
Corrected code:
char * msg_prefix = "APGM";
⋮
if ( (memcmp(msg_prefix,"APGM", 4)==0)

Comparing a function address to 0 or NULL

Problem: I received one of the following warnings:
  • the address of 'int listlen(int, int)' will neverbe NULL [-Waddress]
  • the address of ’farf1’ will never be NULL [-Waddress]
Solution: The compiler issues a warning when anidentifier address is compared to 0 or NULL because the address ofan identifier will never be NULL. The following example shows codethat generates the warning:
  getFarf8(fs->pfs_rType, 2, &farf1, error);
⋮
#define getFarf8(rtype, ord, farf, error)
  {
⋮
  if (farf != NULL)
    memcpy(farf, &fac8.ifacadr, sizeof(fac8.ifacadr));
⋮
  }
Investigate your code to ensure that it is correct. Forexample, ensure that the comparison is coded correctly or that itis correct to specify the address of an identifier instead of theidentifier itself.
Note: The -Waddress warning can be valuable in detectinglegitimate code problems; therefore, consider keeping the warningenabled to improve code quality.


参考

[1] http://pic.dhe.ibm.com/infocenter/tpfhelp/current/index.jsp?topic=%2Fcom.ibm.ztpf-ztpfdf.doc_put.cur%2Fcommon%2Fm1rhwadr.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值