C – No expected warnings from GCC

No expected warnings from GCC… here is a solution to the problem.

No expected warnings from GCC

World

I’m now porting some 32-bit C code to a 64-bit platform.

For the following code, I think GCC should give a warning when I add the option
-Wall -Wconversion -Wextra" to compile the code for a 64-bit platform (x86_64 not IA64).
However, I didn’t receive any warning….

int len = strlen(pstr);

Oddly enough, when I change the code to the following, I can get a warning about the conversion between “size_t” and “int”

size_t sz = strlen(pstr);
int len = sz;

Environmental Information:

GCC version 4.4.7

Linux dev217 2.6.32-358.el6.x86_64 #1 SMP Fri Feb 22 00:31:26 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

Any ideas?

Edit:
I can verify this with a very simple program.

[jsun@/tmp]

[jsun@/tmp]cat test1.c

#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main()
{

int len = strlen("testllllll");

printf("len is %d\n", len);

return 0;
}

[jsun@/tmp]gcc -Wall -Wconversion -Wextra test1.c

[jsun@/tmp]

After modifying the code a bit:

[jsun@/tmp]

[jsun@/tmp]cat test1.c

#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main()
{
    size_t sz = strlen("test111111");
    int len = sz;;

printf("len is %d\n", len);

return 0;
}

[jsun@/tmp]gcc -Wall -Wconversion -Wextra test1.c

test1.c: In the function “main”:

test1.c:8: Warning: Converting from “size_t” to “int” may change its value

[jsun@/tmp]

Solution

gcc optimizes the strlen() function because it operates on const strings (the result is known at compile time). It may replace the result with a const number, so no conversion is done here.

Update: Reference
http://gcc.gnu.org/onlinedocs/gcc-4.4.7/gcc/Other-Builtins.html

So strlen and many other functions are built-in unless -fno-builtin is specified (or -fno-builtin-function is specified for individual functions).
You can add -fno-builtin-strlen to your gcc options. If there is a type conversion, it should warn about the type conversion.
Or you can try using the variable with strlen(). GCC will not optimize that

Related Problems and Solutions