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?
Related
Why is these code giving me a RUNTIME SIGSEGV ERROR. I have tried running the code and works perfectly in codeblocks but some IDE is giving me these error.
It takes a Fibonacci series then modulus each number in the series and only takes up the numbers at eve places till a single number is obtained.
for example:input 1
9
{0 1 1 2 3 5 8 13 21}->{0 1 1 2 3 5 8 3 1}->{1 2 5 3}->{2 3}->3
#include <stdio.h>
int main(void) {
// your code goes here
int n,j,k,r,o;
o=0;
// printf("enter the number of test cases: ");
scanf("%d",&n);
int s[n];
int a;
a=n;
while(n!=0)
{
r=k;
int e[k/2];
int m;
scanf("%d",&k);//enter say 9
if(k!=1)
{
int i[k];
i[0]=0;
i[1]=1;
for(j=0;j<k;j++)
{
if(j>1)
{
i[j]=(i[j-2]+i[j-1])%10;
}
}
while(r!=1)
{
m=0;
for(j=0;j<r;j++)
{
if(j!=0)
{
if(j%2!=0)
{
e[m]=i[j];
m++;
}
}
}
for(j=0;j<k/2;j++)
{
i[j]=e[j];
}
r=r/2;
}
s[o]=e[0];
o++;
n--;
}
else
{
return 0;
}
}
if(k!=1)
{
for(j=0;j<a;j++)
{
printf("%d\n",s[j]);
}
}
return 0;
}
I want to know which point in the code is trigerring the error i know little about these error(like acessing array beyond bonds) can you explain me that?
Your k variable is uninitialized when you first access it at
r=k;
int e[k/2];
This means that it is equal to whatever happened to be stored at that memory location before. This could be any random number and is very bad.
On the next line you declare an array e[k/2] with size k/2, but since k was never initialized, this could be any size. If k happens to be negative, I get a segmentation fault at that line.
To fix this issue, you need to initialize all your variables before using them.
A segmentation fault (SIGSEGV) is what occurs if you try to access memory that isn't allocated to your program by the operating system.
To help with debugging these errors, run your code in the debugger. This can then take you directly to the line where the segmentation fault occured.
just put the scanf("%d",&k);above r=k;
A SIGSEGV is an error(signal) caused by an invalid memory reference or a segmentation fault. You are probably trying to access an array element out of bounds or trying to use too much memory.
also. i am not sure about the return 0; in the else statement.
i haven't run the code so i may be mistaken but it should be return 1; instead of return 0;
if(j!=0)
{
if(j%2!=0)
{
e[m]=i[j];
m++;
}
}
you can replace it with if(j != 0 && j%2 != 0)
I know this ques you are referring to... This is not how you supposed to solve it... You have to find the number which will left in O(1) time... As the odd places are being removed, we have to worry only about even places... Now those even places may become odd when divided by two repeatedly... Hence there is a fix number of steps which convert the whole array in a single element... At each point of this step even placed number is divided by 2, hence there will be only one even placed number who doesn't become odd placed in between or after these steps... You have to find this number just by looking N, at least i did the same... This is just a hint, if it is unclear , i can explain more logic in comment... Upvote😝
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.
This question already has answers here:
Generating all Possible Combinations
(12 answers)
Closed 9 years ago.
I have a problem that I need some help in figuring out. I was hoping I could get a few pointers on a better way to approach what i'm doing. My main issue is a few lines below (//This is whats hanging me up) and described at the bottom of page.
I need to permutate all possible outcomes of a phone number: (not just dictionary words)
I.E. 222-2222
Should output a list 3^7 long with all the possible permutations of a,b,c
I.E.
AAAAAAA
AAAAAAB
AAAAAAC
AAAAABA // THIS IS WHATS HANGING ME UP
AAAAABB
AAAAABC
AAAAACA // HERE TOO AND SO ON
MY CODE (purposely shortened for testing) GIVES ME:
AAAA
AAAB
AAAC
AABC
AACC
ABCC
ACCC
BCCC
CCCC
I'm a beginning programming student so my knowledge goes as far as using for, while, if, statements and grabbing individual chars from the array.
Here's what my code looks like so far: (this is a part of a function. Code missing)
char alphaFunc(char n[]){
int d1=n[0]-48;
int d2=n[1]-48;
int d3=n[2]-48;
int d4=n[3]-48;
int d5=n[4]-48;
int d6=n[5]-48;
int d7=n[6]-48;
int a=0,b=0,c=0,d=0,e=0,f=0,g=0;
int i=0;
char charArray[10][4]={ {'0','0','0'},{'1','1','1'},{'A','B','C'},
{'D','E','F'},{'G','H','I'},{'J','K','L'},{'M','N','O'},
{'P','R','S'},{'T','U','V'},{'W','X','Y'} };
while(i <=14){
printf("%c%c%c%c\n", charArray[d1][a],
charArray[d2][b],charArray[d3][c],charArray[d4][d],
charArray[d5][e],charArray[d6][f],charArray[d7][g]);
g++;
if(g==3){
g=2;
f++;
}
if(f==3){
f=2;
e++;
}
if(e==3){
e=2;
d++;
}
I'm not exactly looking for someone to do this for me I just need a little help in figuring out which sort of statement will work b/c when you have a digit get to CharArray[d-][a] location [3] and reset it to [0] it sends you to a different part of the loop. (hope that makes sense).
Since the values of charArray are constant, I would recommend making it a global variable, rather than declaring it in your function. In addition, since some numbers have 4 letters, whereas others have 3, you may want to look into using a jagged array to represent it.
As far as printing the permutations you can get from a phone number, I think recursion is going to be your friend. Assuming you can store the phone number in an int array, the following should work:
public void printPermutations(int[] phoneNumber)
{
printPermutations(phoneNumber, 0, String.Empty);
}
private void printPermutations(int[] phoneNumber, int index, string permutation)
{
if(index >= phoneNumber.Length)
{
// If we've reached the end, print the number
printf(permutation + "\n");
}
else
{
// Otherwise, generate a permutation for each
// character this digit can be
int digit = phoneNumber[index];
char[] chars = charArray[digit];
for (int i = 0; i < chars.Length; i++)
{
printPermutations(phoneNumber, index+1, permutation + chars[i]);
}
}
}
I'm just a beginner at C.
I'm trying to make a simple program to arrange the user-entered digits in ascending order. I have figured out the solution but can't understand why my other code wouldn't work :(
-------------------------------------------------------------------------
working code:
-------------------------------------------------------------------------
#include <stdio.h>
int main()
{
int i,j,num[10];
printf("Enter 10 numbers\n");
for (i=0;i<10;i++)
{scanf("%d",&num[i]);}
for (i=0;i<9;i++)
{
for (j=i+1;j<10;j++)
{
if (num[i]>num[j])
{
num[i]+=num[j];
num[j]=num[i]-num[j];
num[i]=num[i]-num[j];
}
}
}
printf("The numbers in ascending order are:");
for (i=0;i<10;i++)
{
printf(" %d",num[i]);
}
return 0;
}
-------------------------------------------------------------------------
code that won't work:
-------------------------------------------------------------------------
#include <stdio.h>
int main()
{
int i,j,num[10];
printf("Enter 10 numbers\n");
for (i=1;i<=10;i++)
{scanf("%d",&num[i]);}
for (i=1;i<10;i++)
{
for (j=i+1;j<=10;j++)
{
if (num[i]>num[j])
{
num[i]+=num[j];
num[j]=num[i]-num[j];
num[i]=num[i]-num[j];
}
}
}
printf("The numbers in ascending order are:");
for (i=1;i<=10;i++)
{
printf(" %d",num[i]);
}
return 0;
}
In the latter program, numbers appear out of order, and there even are numbers that haven't been entered.
My question is, isn't it basically the same code? Just that in the latter program numbers would be stored from num[1] to num[10] instead of num[0] through num[9]?
Does it have something to do with array definitions?
It seems I have serious misconceptions, please help me out!
In C, when you have int num[10];, your indexes need to go from 0 to 9, never to 10. So look over your code, if any i or j ends up with a value of 10 any time during the program run, that's bad news.
Indexes in C go start from 0. so when you declare an array of size 10, and you try to get element at index 10, you're actually getting the 11th element. Since you haven't defined the 11th element, the array will most likely get some random numbers from memory, which is why you are noticing numbers you have note entered.
Since you are new to programming, I would suggest taking the time now to really learn about how C manages memory, and how different data structures access the memory. It might be a little boring now, but you'll save yourself some headaches in the future, and you will start to build good habits and good practices, which will lead to writing good, optimal code
for(i=0;i<9;i++) //**i<9**
for (j=i+1 ...)
If i=8 then j=9 , everything is OK.
In second code snippet:
for(i=0;i<10;i++) //**i<10**
for (j=i+1 ...)
If i=9 then j=10, so you try to access num[10] and it gives you error.
If you want to access num[10] then you must declare array int num[11] and then you can access num[10].
Array Basics
int num[10]
Capacity of array = 10
Every element of this array are integer.
First element index is 0. So If you want to access first element , num[0]
Last element index is 9. So If you want to access last element, index must be length of array - 1 , so num[9]
There are 10 elements in the array and they are :
num[0] , num[1] , num[2] , num[3] , num[4] , num[5] , num[6] , num[7] , num[8] and num[9]
You can learn further at http://www.cplusplus.com/doc/tutorial/arrays/
In your non-working example, you have invalid memory accesses. For example, when i = 9 and j = 10, you access num[10], which is invalid memory.
Welcome to programming! I believe you are a bit confused about how arrays are indexed in C.
Arrays in most languages (including C) are known as zero-indexed arrays. This means the start of an array is always at position 0. So if you make int num[10], trying to access num[10] isn't actually a valid call at all, because the start is num[0]. Hence you can only access from num[0] to num[9].
It's an easy mistake to make, even though I've been programming for years sometimes when it's been a long night I'll still make silly array indexing issues.
In your other code example, you were doing this:
int num[10];
for(int i = 1; i <= 10; i++) {
//...
}
That means you have an array with ten spaces [0-9], and for the last part of your for loop, you were trying to access num[10] which doesn't exist.
Your working example goes from 0-9 and never tries to read num[10], so it works.
Arrays in C, as in most languages, start with position 0 and count that as position one. So the last element of your array would be the size you entered when you declared the variable, minus one.
So I have only ever programmed in c++, but I have to do a small homework that requires the use of c. The problem I encountered is where I need a loop to read in numbers separated by spaces from the user (like: 1 5 6 7 3 42 5) and then take those numbers and fill an array.
the code I wrote is this:
int i, input, array[10];
for(i = 0; i < 10; i++){
scanf("%d", &input);
array[i] = input;
}
EDIT: added array definition.
any suggestions or hints would be very highly appreciated.
Irrespective of whatever is wrong here, you should quickly learn to NEVER write code that does not check the return value from any API call that you make. scanf returns a value, and you have to be interested in what it says. If the call fails, your logic is different, yes?
Perhaps in this case it would tell you what's going wrong. The docs are here.
Returns the number of fields
successfully converted and assigned;
the return value does not include
fields that were read but not
assigned. A return value of 0
indicates that no fields were
assigned.
This code working good.
If your numbers is less than 10, then you must know how many numbers is before you start reading this numbers, or last number must be something like 0 to terminate output then you can do while(true) loop, but for dynamically solution you must read all line into string and then using sscanf to reading numbers from this string.
You need the right #include and a proper main. The following works for me
#include <stdio.h>
int main(void) {
/* YOUR CODE begin */
int i, input, array[10];
for (i = 0; i < 10; i++) {
scanf("%d", &input);
array[i] = input;
}
/* end of YOUR CODE */
return 0;
}
i'm not a c programmer but i can suggest an algorithm which is to use scanf("%s",&str) to read all the input into a char[] array then loop over it and test using an if statment if the current char is a space, if it is then add the preceeding number to the array