SIGSEGV Error in short C code - c

So, as someone who is fairly new to C, I came across my first SIGSEGV Error.
It appeared in a short C program that is meant to be a "guess the number" game. It consists of a self-defined function that compares two numbers and a do-while loop with an input inside it.
The start and the do-while loop:
#include<stdio.h>
int checkNum(int num1, int num2); //See below for explanation
int main(void) {
int input=0, rand=3; //"Random" number has fixed value for testing
do {
printf("Enter number from 0-10: "); //There is not actual range yet
scanf("%d",input); //Get input
} while(checkNum(input, rand)); //Checks if difference != 0
}
The function for comparing:
//Function for comparing input with "random" number
int checkNum(int num1,int num2) { //The two numbers that get compared; First one: input, Second one: "random" rumber
if(num1==num2) {
printf("Correct. The random number was %d",num2);
} else if(num1<num2) {
printf("Wrong. The random number is bigger.");
} else if(num1>num2) {
printf("Wrong. The random number is smaller.");
}
return num2-num1; //Return the difference, leads to 0 if equal
}
I suspect the error to be in the function, caused by a missing use of a pointer, but as far as I understand pointers, they don't seem necessary here: I don't change a single variable in the function, and the return only subtracts two values (which are given I assume).
I hope my error isn't too stupid, and I'd like to thank everyone who can help or tries to.
(I can post my processor values, altough I am not sure if that will help; If any more information is needed for debugging, please tell me)

This:
scanf("%d",input); //Get input
should be:
scanf("%d",&input); //Get input
^^^
Pro tip: always compile with warnings enabled (e.g. gcc -Wall ...) and the compiler will happily point out simple mistakes such as this, saving you a lot of time and grief.

Related

Debug-print for loop omitting 1st value

I was debugging a low level program, I had to ensure that my array exp have all values I expect it to have. So I wrote a code snippet that prints my array to help debug it. Problem is standard library isn't available so I need to use my own code.
My code snippet:
int test=0;char val[5]={};
int l=0;
for(int k=0;exp[k]!=0;k++)
{
test=exp[k]; //taking in value
int_to_ascii(test, val);
print_char(val,2*l,0xd);
for(int m=0;val[m]!='\0';m++)//clearing out val for next iteration
val[m]='\0';
l=k*0xA0; //next line
}
exp is an integer array..
code for int_to_ascii:
if(src==0)
{
stack[i++]='\0'; //pushing NULL and 0 to stack
stack[i++]='0';
}
else
{
while(src!=0) //converting last digit and pushing to stack
{
stack[i]=(0x30+src%10);
src/=10;
i++;
}
}
i--;
len=i;
while(i>=0)
{
dest[len-i]=stack[i]; //popping and placing from left to right
i--; //inorder not to get reversed.
}
print_char works because I use it to print entire window and interface. It basically takes
char* szarray,int offset,int color.
I was yelling at my computer for nearly 2 hours because I thought my array is incorrect but it shouldn't be, but the actual problem was in this debug code.It doesn't print exp[0].
When it should output:
20480
20530
5
It just prints
20530
5
I even tried brute forcing values into exp[0]. If I give any value except 20480 into that, it will print invalid characters into first entry,like this:
20530P\. ;not exact value, demonstration purpose only
5
I think something is off in int_to_ascii, but that also is extensively used in other parts without any problems.
Any one have any idea with it?

How can I print from (whatever user input integer) to 0 and then back to the integer without using recursion? (Computing class assignment)

My professor wants use to ONLY use while loops and call 2 different functions, which I have done. I am really stuck on how to tweak this so that if I put in, say, 16, that it will list 16 to 0 on separate lines, as well as 0 to 16 again on separate lines. I can do this with recursion very well for some reason, but without being able to do that, I am lost on how to make this work.
My computing class is learning with C language, so that is what my code is written in.We are also not required to validate input and are under the assumption that the user is entering valid input (a positive integer). Any tips are well appreciated! Thank you.
#include <stdio.h>
void loop_down_to_zero(int number);
void loop_up_to_int(int number);
int main(int argc, char* argv[])
{
printf("please enter a positive integer:");
int number;
number = ("%d" >= 0);
loop_down_to_zero(number);
loop_up_to_int(number);
scanf("%d", &number);
printf("****\n");
return 0;
}
void loop_down_to_zero(int number)
{
while ( number > 0 )
{
loop_down_to_zero(number - 1);
printf("\n%d", number-1);
}
}
void loop_up_to_int(int number)
{
while ( number >= 0 )
{
loop_up_to_int(number+ 1);
printf("%d\n", number+1);
}
return;
}
This is not C
number = ("%d" >= 0);
At least not any meaningful C.
Replace it by the actual input-reading a few lines later,
scanf("%d", &number);
So that you have a meaningful number for the calls to the functions.
That should solve you immediate blocking point.
Then have a look at the hint at your next problem, provided as a comment by arvind:
"Also your number is positive and you're incrementing it so, while ( number >= 0 ) doesn't make any sense." You probably want something including (current_number <= number).
Then for a recursion solutin use if instead of while.
Then to get you started on a non-recursive solution, actually change within the loop body the variable you are testing inside the loop condition;
otherwise you have a guaranteed endless loop killing your programs functionality.
(I intentionally do not give a complete solution, according to the compromise described here, How do I ask and answer homework questions? The asker-side of which OP has well honored in my opinon.)

Error when using array elements in conditional statements in C

I have done my fair share of studying the C language and came across this inconsistency for which I cannot account. I have searched everywhere and reviewed all data type definition and relational syntax, but it is beyond me.
From the book C How to Program, there is a question to make a binary to decimal converter where the input must be 5-digits. I developed the follow code to take in a number and, through division and remainder operations, split it into individual digits and assign each to an element in of an array. The trouble arises when I try to verify that the number entered was indeed binary by checking each array element to see whether it is a 1 or 0.
Here is the code:
#include <stdio.h>
int power (int x, int y); //prototype
int main(void)
{
int temp, bin[5], test;
int n=4, num=0;
//get input
printf("%s","Enter a 5-digit binary number: ");
scanf("%d", &temp);
//initialize array
while(n>=0){
bin[n]=temp/power(10,n);
temp %= power(10,n);
n--; }
//verify binary input
for (test=4; test>=0; test--){
if ((bin[n]!=0)&&(bin[n]!=1)){
printf("Error. Number entered is not binary.\n");
return 0; }
//convert to decimal
while(n<=4){
num+=bin[n]*power(2,n);
n++; }
printf("\n%s%d\n","The decimal equivalent of the number you entered is ",num);
return 0;
}
//function definition
int power(int x, int y)
{
int n, temp=x;
if(y==0) return 1;
for(n=1; n<y; n++){
temp*=x; }
return temp;
}
Could someone explain to me why regardless of input (whether: 00000, or 12345), I always get the error message? Everything else seems to work fine.
Thank you for your help.
Update: If the if statement is moved to the while loop before. This should still work right?
Update2: Never mind, I noticed my mistake. Moving the if statement to the while repetition before does work given the solution supplied by sps and Kunal Tyagi.
After this
while(n>=0){
bin[n]=temp/power(10,n);
temp %= power(10,n);
n--; }
n is set as -1 so when you try to convert to decimal the statement bin[n] is actually bin[-1] so it returns you error.
One issue is that, while checking if the number is binary or not, you are returning at wrong place. You need to return only if the number is not binary. But you are returning outside the if condition. So your program returns no matter what the input is.
for (test=4; test>=0; test--){
if ((bin[test]!=0)&&(bin[test]!=1))
printf("Error, numbered entered was not binary.\n");
// Issue here, you are returning outside if
return 0; } //exit program
You can change that to:
for (test=4; test>=0; test--){
if ((bin[test]!=0)&&(bin[test]!=1)) {
printf("Error, numbered entered was not binary.\n");
// Return inside the if
return 0; // exit program
}
}
There is one more issue. Before you convert your number to decimal, you need to set n = 0;
//convert to decimal
n = 0; /* need to set n to zero, because by now
n will be -1.
And initially when n is -1, accessing
bin[-1] will result in undefined behavior
*/
while(n<=4){
num+=bin[n]*power(2,n);
n++; }
This looks like a homework, but your issue is in the brackets. More specifically line 23. That line is not part of the logical if statement despite the indentation (since that doesn't matter in C).
No matter what, the program will exit on test=4 after checking the condition.
Solution:
if ((bin[test]!=0)&&(bin[test]!=1)) { // << this brace
printf("Error, number entered was not binary.\n");
return 0; } } //exit program // notice 2 braces here

Getting segmentation fault after while loop

Hi i have a project for tommorrow which i want to finish but im stuck. Im pretty new at this so don't be harsh.Basicly i want my program to ask how many numbers did the user play. How much money, after it asks for the lottery numbers and puts then in a border,then it asks for the users numbers,puts in on a second border and then i want to compare the 2 of them and if they have a same number it will add to 'sum'.
#include <stdlib.h>
int main()
{
int k[20],i;
int k2[12],f;
int numbers,sum,n,l,num;
float money,winnings;
l=0;
sum=0;
printf("How many numbers from 1 to 12?\n");
scanf("%d",&num);
printf("How much money?\n");
scanf("%f",&money);
for (i=0;i<19;i++)
{printf("Give lottery numbers\n");
scanf("%d",&k[i]);}
while (l<num){
printf("Give your numbers\n");
scanf("%d", k2 + f); !!fixed!!
l++;}
for (f=0;f<num;f++){
for (i=0;i>19;i++){ !!fixed!!
if ((k[i])==(k2[f])) !!! and here i think its a mistake.
{
sum=sum+1;
}
}
}
printf("You got %d numbers out of %d",sum,num);
if ((sum=1) && (num=1));
{winnings=(money*2,5);
printf("Won %f",winnings);}
if ((sum=1) && (num=2));
{winnings=(money*1);
printf("won %f",winnings);}
if ((sum=2) && (num=2));
{winnings=(money*5);
printf("Won %f",winnings);}
system("pause");}
It doesn't appear that f has ever been initialized to anything. Therefore,
scanf("%d",k2[f]);
Will result in undefined behavior, and is the likely cause of the crash.
Additionally, you need to fix your indentation. Furthermore, your loop is off by one. You initialize l to 1, then execute the following loop, whose apparent purpose is reading num numbers:
while (l<num){
So, if, for example, "1" was entered, in order to read only one number, the body of the loop will never execute, since the comparison "1<1" will be false.
It's likely there are other problems with this code, hard to analyze it due to bad indentation.
This loop
for (i=0;i=19;i++){
will never end since i=19 will evaluate to always true.
I think that the intention was:
for (i=0;i<19;i++){
Instead of l, what you probably intended, you are using f, which, as Sam Varshavchik spotted already, is not initialized.
Additionally, you are not passing a pointer to scanf: scanf("%d", k2[f]);. You need scanf("%d", k2 + l); instead, or scanf("%d", &k2[l]), if you prefer.

Why i'm getting runtime error in ideone and codechef compiler and not in my terminal?

I have just started competitive programming in SPOJ.I'm confused from sometime why i'm getting runtime error in ideone.The question is:
A positive integer is called a palindrome if its representation in the decimal system is the same when read from left to right and from right to left. For a given positive integer K of not more than 1000000 digits, write the value of the smallest palindrome larger than K to output. Numbers are always displayed without leading zeros.
Input
The first line contains integer t, the number of test cases. Integers K are given in the next t lines.
Output
For each K, output the smallest palindrome larger than K.
Example
Input:
2
808
2133
Output:
818
2222
My program:
#include <stdio.h>
int main(void)
{
int t,i,reverse,same;
scanf("%d",&t); //t is no. of test cases
int num[t]; //num[t] is array of t elements
for(i=0;i<t;i++)
scanf("%d",&num[i]);
i=0; //since i will be equal to t therefore i is assigned to 0.
while(t--)
{
if(num[i]<=1000000)
{
while(num[i]++)
{
reverse=0;
same=num[i];
while(same>0)
{
reverse=reverse*10;
reverse=reverse+same%10;
same=same/10;
}
if(reverse==num[i])
printf("%d",reverse);
printf("\n");
if(reverse==num[i])
break;
}
}
i++;
}
return 0;
}
I don't know where i'm wrong.I'm sorry i'm asking this question may this question is asked by someone before.I tried to find the result but could not get the answer.Thankyou in advance and sorry for my bad english.
The question doesn't say that the number will be less than 1000000. It says that the number has less than 1 million digits. A number with a million digits looks like this
591875018734106743196734198673419067843196874398674319687431986743918674319867431986743198674319876341987643198764319876341987643198764319876431987643198763419876431987643198764319876139876...
You can't use scanf to read a number that has a million digits, and you can't store that number in an int.
The most likely reason for your error to occur is some memory fault. Keep in mind that online judges/compilers limit your available memory and if you try to allocate/use more memory than available, you get a runtime error. This also happens on your machine, but usually you have a lot more memory available for your program than in the case of online judges.
In your case, you could reduce the memory usage of your program by changing the data type of the num array from int to something like short or even char.

Resources