3
votes

World

I am now porting some 32 bit C code to 64 bit platform.

For the following code, I think there SHOULD be warnings by GCC when I add the option
"-Wall -Wconversion -Wextra" to compile the code to 64 bit platfrom(x86_64 not IA64).
However, I don't get any warnings...

int len = strlen(pstr);

Curiously, when I change the code to the following and I can get the wanrings about conversion between "size_t" and "int"

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

Environment info:

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 why?

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 little:

[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 function ‘main’:

test1.c:8: warning: conversion to ‘int’ from ‘size_t’ may alter its value

[jsun@/tmp]

1
so do you #include <string.h>? if you don't, the implicit function declaration would return int. can you post your source file and gcc output?tristan
I have pasted the code in the original postJacky
I don't have the compiler to test this at the moment, but you might try changing it to call strlen() on an argument passed in from main(int argc, char *argv[]) and see if it produces a warning (strlen(argv[1]) for example). Compilers can optimize strlen(conststring) to the exact value (10 in your example) and don't even include a call to strlen. In that situation, it might not result in a warning.Mark Wilkins
I get the same warning (on the correct lines) for both your code examples (gcc 4.7.3).vanza
What @MarkWilkins said. I tested this with gcc4.8.1, and it both optimizes away the call to strlen and reports a warning, both with -O0 and -O2rici

1 Answers

4
votes

gcc optimized the strlen() function as it operates on a const string (the result is known at compile time). It might replace the result with an const number so no cast is done here.

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

So strlen and many other functions are built-in functions unless -fno-builtin is specified (or -fno-builtin-function is specified for an individual function). you can add -fno-builtin-strlen to your gcc options. It should warn on cast if there is casting. Or you can try using a variable with strlen(). gcc would not optimize that