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.
参考