#include <stdio.h>
main()
{
int n;
n+=2;
printf("sum=%d", n);
return 0;
}
Here the 'Sum'=2
Another program:-
#include <stdio.h>
main()
{
int n,a=2;
n+=a;
printf("sum=%d", n);
return 0;
}
here the output 'sum' = 3
WHY so?? What is the problem in the code??
This is Undefined Behavior. Using uninitialized variables (n in both snippets) can produce unexpected results, meaning that running the first code twice might produce different outputs. There is no "correct" output for either of the codes, but if you'll set n to a specific value in both codes, you'll start getting consistent results.
This is UB (Undefined Behavior):
main()
{
int n;
printf("sum=%d", n);
return 0;
}
This is not:
main()
{
int n = 0;
printf("sum=%d", n);
return 0;
}
When you don't assign a value to a local variable in C, its value is undefined. So in some cases it will be 0, in some 1, in some, something else entirely. You cannot know what it will be and you should never rely on it. Instead, initialize your local variables:
int n = 0; // initialization
n += 2;
printf("sum=%d", n); // will always print 2
Related
I am writing a C program to sum up prime numbers below a certain limit (9 for now). I expect 17 but the compiler gave me an unexpected output of 32781.
#include <stdio.h>
#include <stdbool.h>
bool isprime(int n);
int main(){
const int LIMIT=9;
int sum;
for (int j=1;j<LIMIT;j++){
if (isprime(j)){
sum+=j;
}
}
printf("%d",sum);
return 0;
}
bool isprime(int n){
if (n<=1){
return false;
}
else{
for(int i=2;i<n;i++){
if (n%i==0){
return false;
break;
}
}
return true;
}
}
Does anyone understand why this happened?
You declarred int sum; but didn't give sum a starting value, so it's basically reading garbage from memory. In c you need to initialize your variables properly. int sum = 0; should fix the problem.
If you are using clang as your compiler, compiling using -Wall should warn you about this.
Local variables are not initialized, so you need to initialize at declaration or before use.
int sum = 0;
or...
int sum;
for (sum = 0; bla; bla)
If the variable had been declared globally (outside of any function... main is a function) it will automatically initialize to 0.
#include <stdio.h>
int a;
int main(void)
{
int b;
printf("%d\n%d\n", a, b);
return 0;
}
Variable 'a' will be 0 and 'b' will be garbage because it's an uninitialized local variable.
Code-1: No warnings - No errors ... everything works fine
#include <stdio.h>
int main()
{
int r = 1;
printf("using %d\n", r);
for (int k = 1; k <= 2; k++)
{
int r = r * 2;
}
return 0;
}
Code-2: Wrong
#include <stdio.h>
int main()
{
int cnt = 1;
printf("using %d\n", cnt);
{
int cnt = cnt * 2;
}
return 0;
}
compiler response:
'cnt' is used uninitialized in this function [-Werror=uninitialized]
int cnt = cnt * 2;
So, I understand there is some difference between the loop and block in this case, but I am unable to figure out. Can anyone tell me how the scope of a variable works here?
They both have exactly the same problem i.e. r and cnt are self-initialized in respective programs.
This is potentially undefined because of use of uninitialized variables (which has indeterminate value) if they happen to have trap representation.
gcc happens to detect it one case and doesn't in the other case. gcc has -Wuninitialized -Winit-self options but it still doesn't detect the first case even with these options. Regardless, the issue remains (and the same) in both.
I am new to the C.Sc course and we are taught C program.
I was trying some of the basic stuff. Currently I am learning User-Defined-Function.
The following code is the one I was trying with. I know it is pretty simple but I am not able to understand why it is producing such weird output.
#include <stdio.h>
int add(int a); //function declaration
int main (void)
{
int b,sum;
printf("\nEnter a number: ");
scanf("%d", &b);
sum = add(b); //function calling
printf("\nSum: %d\n\n", sum);
}
int add(int a) //function definition
{
int result;
for(int i = 0; i < a; i++)
{
result = result + i;
return result;
}
}
The output for 1 is 32743
The output for 2 is 32594
The output for 3 is 32704
The weird thing is output change each time for the same number.
It's just weird considering my experience in C.Sc. till date. Kindly explain what the program is doing.
This is the right place to post problems like this. Right?
You forget to initialize result.
int result = 0;
Explanation : If you do not initialize the variable, it will have a "random" number, and then you are going to get "random" output
Also :
You also forgot to return something if a = 0, or a negatif number !
And your main NEED to return a int.
Also, there is no point to do a loop since you return inside of it, you always going to return 0 in the loop.
Here is a correction of your code :
#include <stdio.h>
int add(int a); //function declaration
int main (void)
{
int b,sum;
printf("\nEnter a number: ");
scanf("%d", &b);
sum = add(b); //function calling
printf("\nSum: %d\n\n", sum);
return 1;
}
int add(int a) //function definition
{
int result = 0;
for(int i = 0; i < a; i++)
{
result = result + i;
}
return result;
}
Exemple with 10 as input : https://ideone.com/6BjM6y
You need to initialize result,
int result = 0;
In your code, result is not initialized so at the
result = result + i;
line, you use whatever value result has and it's not possible to determine which value is that because it's a garbage value.
In c, variables are not automatically initialized for performance reason, with a few exceptions, the most notable are
Local variables with static storage class.
Global variables.
when you leave a variable uninitialized, then trying to read it's value is considered undefined behavior.
In response to your comment
The problem is that you return after adding 0 to result which is 0, so move the return result; outside of the for loop and it should work.
You need to initialize the variable result. Since it is bot initialized, the compiler initializes it with a default value, which could be a "funky" mumber. To fix this, initialize result in your Add() function to:
int result = 0;
Another thing: your return statement is inside the for-loop. This means that the for-loop will terminate at the end of the first loop since there is a return statement that will terminate the function. To fix it, change your function to:
int result;
for(int i = 0; i < a; i++)
{
result += i; // shorthand way of writing result = result + i. Same end result
}
return result; // should be outside the loop
My Code:
#include <stdio.h>
int main(int argc, char*argv[]){
int n = argc;
int i, a, b, sum;
for(i = 0; i < n; i++){
sscanf(argv[i], "%u", &a);
b = a + sum;
sum = b;
}
printf("%d\n", sum);
return 0;
}
This piece of code should do ./a 0 1 2 3 must write terminal 6 But writes 42423.
The aim of the program was to issue the command-line arguments amount. But he does not make it correct angulation.
argv[0] holds the name of the executable which most likely you don't want to include in the loop. so, you need to start the loop from i=1.
As per your input, the argv[0] does not contain a numeric value hence causing a failure to sscanf(), leaving a uninitialized.
So, in your code, the primary issue is with,
b = a + sum;
where, for the first iteration, a and sum are both uninitialized local variables having indeterminate value. So, for the very first loop, you're invoking undefined behavior.
Also, a being an int, you need to use %d format specifier for it.
Two things to mention:
Always check for the return value of scanf() family for success.
Always initialize your local variables.
You are getting garbage value because you are not initialized varuiable sum on declaration.
Just initialize is as sum = 0 and u will get expected result.
Or u can use below code also.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char*argv[]){
int n = argc;
int i, a, b, sum=0;
for(i = 0; i < n; i++){
a = atoi(argv[i]);
sum += a;
}
printf("%d\n", sum);
return 0;
}
The code runs until it reaches the statement:
printf("%d", sumOccur(input));
The code:
#include <stdio.h>
#include <stdlib.h>
int sumOccur(int A[]);
int main(){
int input[6] = {1,1,1,2,2,3};
printf("%d", sumOccur(input));
return 0;
}
int sumOccur(int A[]) {
int sum, i;
while(A[i]!='\0'){
sum += A[i];
i++;
}
return sum;
}
If I have made any silly mistakes please oblige.
It's not the printf() crashing. It's sumOccur(). Your array has no \0 value in it, so your while() never terminates and you end up in a near-infinite loop and run off the end of the array.
The array is an array of numbers, not a string, so there is no reason whatsoever to think there there would be a null-terminator on the values. null terminators are for strings, not arrays of numbers.
In your function int sumOccur you have two problems-
1. sum and i are not initialized just declared. Initialize both to 0 .
2. Also while(A[i]!='\0') ain't going to work as expected as your array doesn't have that value in it.
Your code invokes undefined behaviour: you access A[6] and subsequent inexistent entries in sumOccur trying to find a final 0 in the array, but you do not put one in the definition of input in the main function.
-------- cut here if you are not interested in gory implementation details --------
The array is allocated on the stack, very near the top since it is instantiated in the main function. Reading beyond the end until you find a 0 likely tries to read beyond the end of the stack pages and causes a segmentation fault.
Note that you are dealing with an int array,which means it normally won't contain '\0' character.To iterate over the array you need to specify number of elements.Here is the correct way :
#include <stdio.h>
#include <stdlib.h>
int sumOccur(int A[],size_t number_of_elemets);
int main(){
int input[6] = {1,1,1,2,2,3};
//Get the number of elements
size_t n = sizeof(input) / sizeof(int);
printf("%d", sumOccur(input,n));
return 0;
}
int sumOccur(int A[],size_t number_of_elements) {
int sum = 0;
size_t i = 0;
while( i < number_of_elements )
{
sum += A[i];
i++;
}
return sum;
}
You are iterating while A[i] != '\0' but there is no '\0' in the array and also you never initialize sum which is unlikely the cause for a crash but it could be.
You need to pass the number of elements in the array, like this
#include <stdio.h>
#include <stdlib.h>
int sumOccur(size_t count, const int *A);
int sumOccurCHQrlieWay(const int *A, size_t count);
int main()
{
int input[] = {1, 1, 1, 2, 2, 3};
printf("%d", sumOccur(sizeof(input) / sizeof(*input), input));
return 0;
}
int sumOccur(size_t count, const int *A)
{
int sum;
sum = 0;
for (size_t i = 0 ; i < count ; ++i)
sum += A[i];
return sum;
}
int sumOccurCHQrlieWay(const int *A, size_t count)
{
return sumOccur(count, A);
}