Why clang doesn't issued a warning with using uninitialized array?

304 Views Asked by At

I was reading some code from a book,and forget to initialize the array marbles.But I get no warning from clang. here is the code:

/* sum_arr2.c -- 对一个数组的所有元素求和 */
#include<stdio.h>
#define SIZE 10
int sump(int *start,int * end);

int main(void)
{
    int marbles[SIZE];
    long answer;

    answer = sump(marbles,marbles + SIZE);
    printf("The total number of marbles is %ld.\n",answer);
    return 0;
}

/* 使用指针算术 */
int sump(int * start,int * end)
{
    int total = 0;

    while(start < end)
    {
            total +=*start; /* 把值累加到total上*/
            start++;        /* 把指针向前推进到下一个元素 */
    }
    return total;
}

I compiled the code with:

gcc -Wall sum_arr2.c

and got no warning. so I tried

clang -Wall sum_arr2.c

still no warning. when I executed the program

./a.out

The output is some random value.

so I want to ask is it a correct behavior of the compiler, Or a bug?

It seems gcc is just a name not the really gcc compiler:

gcc -v

Configured with: --     prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin13.4.0
Thread model: posix

clang -v
Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin13.4.0
Thread model: posix

can anyone test it on gcc ?

1

There are 1 best solutions below

0
On

Most compilers will only look into one function at a time when they are generating warnings and if you don't look inside the implementation of sump you can't know that the call inside main is wrong. What if sump wrote to the array instead of reading from it? In that case passing an uninitialized array would not be a problem.

int sump(int * start,int * end)
{
    while(start < end)
    {
        *start = 42;
        start++;
    }
    return 17;
}