3

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 ?

Yu Hao
123k50 gold badges252 silver badges305 bronze badges
asked Jun 12, 2015 at 4:06
2
  • Do you have more warnings with gcc -W -Wall sum_arr2.c ? Commented Jun 12, 2015 at 4:21
  • GCC produces a warning with -O3. Commented Jun 12, 2015 at 4:23

1 Answer 1

3

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;
}
answered Jun 12, 2015 at 4:20
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.