Jacky
Jacky

Reputation: 71

No expected warning from GCC

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]

Upvotes: 3

Views: 252

Answers (1)

tristan
tristan

Reputation: 4312

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

Upvotes: 4

Related Questions