C program crashes on printing array - c

I am learning C at the moment, and am trying to build a simple interpreter. It takes one character and one number. The program below only uses 'r' for the char. The 'r' stands for the range (of the natural numbers) and the digit after it specifies the length of the range.
Example Execution:
Enter:
r 9
0 1 2 3 4 5 6 7 8
What happens instead:
Enter:
r 9
And here the program crashes. So I believe the error lies in the printing of the array.
The code in question is here:
#include <stdio.h>
#include <stdlib.h>
int* range(int i) {
int *a=(int*) malloc(i * sizeof(int));
int j;
for(j=0;j<i;j++)
a[j]=j;
return a;
}
void printArray(int a[], int length) {
int i;
printf("\n");
for(i=0;i<length;i++)
printf("%d ", a[i]);
}
int main() {
char c;
int n = 1;
while(n>=0){
printf("\nEnter:\n\t");
scanf("%c %d", c, n);
if(c='r')
printArray(range(n), n);
}
return 0;
}
So what is causing the program to crash?

Your arguments to scanf are wrong, you need
scanf("%c %d",&c, &n);
Your fundamental problem here is that you have no evidence about where the crash is happening, as it happens I bet it's in scanf().
I recommend you adopt two debugging techniques:
a). Add print statements in your code so you know what's happening
b). Use an interactive debugger so you can step through and see what's going on.

Related

CodeChef runtime error(sigsegv)

CodeChef Problem:
Shivam is the youngest programmer in the world, he is just 12 years old. Shivam is learning programming and today he is writing his first program.
Program is very simple, Given two integers A and B, write a program to add these two numbers.
Input
The first line contains an integer T, total number of test cases. Then follow T lines, each line contains two Integers A and B.
Output
Add A and B and display it.
Constraints
1 ≤ T ≤ 1000
1 ≤ A,B ≤ 10000
Example
Input
3
1 2
100 200
10 40
Output
3
300
50
#include <stdio.h>
int main()
{
int T, A, B, i, sum[T];
scanf("%d", &T);
for(i=0;i<T;i++)
{
scanf("%d",&A);
scanf("%d",&B);
sum[i]=A+B;
}
for(i=0;i<T;i++)
{
printf("\n%d", sum[i]);
}
}
Error
Runtime Error SIGSEGV - I searched it, it says array out of bounds.
T has an indeterminate value when you declare sum[T]. Instead, do:
int main()
{
int T, A, B, i;
scanf("%d", &T);
int sum[T];
for(i=0;i<T;i++) ...
Ans you should check the return value of scanf.
If you want to allocate the memory runtime (during the programs execution) it would be more appropriate to use a function such as "malloc". Here is a short example.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int T, A, B, i;
int *sum;
scanf("%d", &T);
if (T <= 0) /*Check if the value of T is appropriate*/
{
fprintf(stderr, "Invalid argument T!\n");
}
/* Dynamically allocate the memory */
sum = (int *)malloc(sizeof(int)*T);
if (sum == NULL)
{
fprintf(stderr, "Failed to allocate memory!\n");
}
for(i=0;i<T;i++)
{
scanf("%d",&A);
scanf("%d",&B);
sum[i]=A+B;
}
for(i=0;i<T;i++)
{
printf("\n%d", sum[i]);
}
/* Free the allocated memory once you are not needing it anymore in
order to avoid memory leaks */
free(sum);
return (0);
}
Note: This is just an example how to avoid the runtime error I have not taken a close look at the rest of the logic related with the for loops.
Declare sum[T] after taking the input value of T

how to use scanf to scan double and char at the same time into a double array in C

I have a project to do which asks me to record the address of two vectors into a double array according to user's input. However. For example, if user writes
3
1 2 3
3 4 5
it means that the vectors are 3 dimensional and the two vectors are (1,2,3)(3,4,5). If user writes,
2
1 2
2 3
it means that the vectors are 2 dimensional and the two vectors are (1,2)(2,3). I need to record the coordinates of these two vectors into two double arrays x, and y. How can I read the coordinates into these two arrays using scanf? (I don't know if the user writes in the correct format, it's possible for them to write letter or other symbol at the place where they are supposed to just write number. If they write chars other than number, i need to return -1.)
my code so far is
double x[100];
char c;
c = getchar();
do {
scanf("%lf",x)}
while (c!= '\n');
As far as I understand your problem, here is a code that should solve it.
#include <stdio.h>
#include <stdlib.h>
#define NB_VECTORS 2 //Increase if you have more than 2 vectors
int* readVector(int size) {
// Allocation fits the size
int* vector = malloc(size*sizeof(int));
//While the vector are the same size it works
for (int i = 0; i < size; i++)
if (scanf("%d", vector+i) != 1)
return null; //bad input
return vector;
}
int main(int argc, char** argv) {
int size;
scanf("%d", &size);
//Each line is vectorized inside vectors[i]
int* vectors[NB_VECTORS];#
for (int i = 0; i < NB_VECTORS; i++)
vectors[i] = readVector(size);
return 0;
}
[EDIT]
returns the number of items it has filled -> cf http://www.cplusplus.com/reference/cstdio/scanf/
Maybe you simply need something like this (simplistic, minimal, no error checking example):
int main()
{
int x[3], y[3];
int dimension;
scanf("%d", &dimension);
if (dimension == 3)
{
scanf("%d %d %d", &x[0], &x[1], &x[2]);
scanf("%d %d %d", &y[0], &y[1], &y[2]);
}
else if (dimension == 2)
{
scanf("%d %d", &x[0], &x[1]);
scanf("%d %d", &y[0], &y[1]);
}
...
return 0;
}
scanf is not a good function for parsing user input. It accepts 2.1sdsa2 as a float with the value 2.1 and it accepts 2.1sdsa2 as an int with value 2. The scanf should only be used when you know that the input is valid.
If you are required to use scanf, you can scan into a string and then write your own parse to check that the input is valid.
A simple example:
#include <stdio.h>
#include <string.h>
int main(void)
{
char s[10];
while (1 == scanf("%s", s))
{
printf("%s\n", s);
if (strcmp(s, "s") == 0) break;
}
return(0);
}
The program continues until the input is s
Example of output:
1 2.0 2.6
1
2.0
2.6
2a 4567 2.a23
2a
4567
2.a23
s
s
Notice that scanf returns when it sees a space. So the input 1 2 3 will be 3 loops (aka 3 substrings returned).
So instead of just printing, you could put your parser inside the while:
while (1 == scanf("%s", s))
{
// Parse the string s and add value to array
}

Push, pop and display functions from one string to a stack

I'm trying to write a program where the user introduces an array numbers and alphabethic characters. Then the program reads the array, if he sees a number, the program should push that number into one stack. However, if he sees an alphabetical character, the last number pushed is popped.
So far I have this code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 20
int top, i;
void push (double stack[], double x, int top)
{
stack[top] = x;
}
int pop (double stack[])
{
double x;
stack [top]=x;
return x;
}
void display (double stack[],int top)
{
int i;
printf ("\n The stack is: ");
for (i=0; i<=top; i++)
{
printf ("%lf\n",stack[i]);
}
}
void main()
{
int r;
int stack[10];
char array[10];
printf("introduce the numbers");
fgets(array,MAX,stdin);
int l;
r=strlen(array);
top=0;
for (l=0;l<=r;l++)
{
int n;
if (isdigit(array[l]))
{
push(stack,array[l],top);
top=top+1;
}
if (islower(array[l]))
{
pop(stack);
printf("you have popped %d", n);
top=top-1;
}
}
display(stack,top);
}
For some reason the program does not work, if I introduce 22a the output is:
you have popped 4194432
The stack is: 50.00000
50.00000
I am particularly interested in how should I write the pop,push and display to make this program work. How can I do it?
First off, your variable n, the value of which you're printing, is uninitialized and contains whatever garbage that was in the memory at the moment of its creation.
Also, why are you printing it? I think you meant to say n = pop(stack);, right? Otherwise this printing is useless.
Throughout your code you're writing loops the wrong way: for (t=0; t<=threshold; t++). This code will make the loop run threshold + 1 times, but you obviously want only threshold, so do for (t=0; t<threshold; t++) instead.
You're also reading (fgets(array,MAX,stdin);) maximum twenty characters into your array, which can hold only ten characters.
To use strlen on an array, you need it to end with zero (null-terminator). In your code array is not necessarily initialized with zeros, so use memset(array, 0, 10); before using array:
Docs on memset
Tutorial on for loops
void main() is wrong
What to read to learn C

How to concat integer and string inside recursive function in C

guys, I want to make a program to generate all combination elements. for example if user input (n) = 3, so the output must be like this :
1
12
123
13
2
23
3
I have a problem to concat integer and string inside recursive function..
Code :
#include <stdio.h>
void rekursif(int m, int n, char angka[100]){
int i;
for(i=m; i<=n; i++){
sprintf(angka, "%s %d", angka, i);
printf("%s \n", angka);
rekursif(i+1,n,angka);
}
}
int main(){
rekursif(1,5,"");
return 0;
}
when I run the program, command prompt is not responding. I guess, the problem is in concation ( sprintf(angka, "%s %d", angka, i); )
please help me to solve this problem. thank you :)
By passing "" as the function argument, you are trying to modify a string literal, which is undefined behavior. Instead, do:
int main(){
char str[100];
rekursif(1, 5, str);
return 0;
}
Be careful with buffer overflow in practice.

scanf infinite loop

This program takes the first number in a file and indicates how many numbers are going to be after it, then does various other things with the numbers that follow.
It seems like scanf is causing an infinite loop when trying to read from the file. WHen I run the program not even the check at 1 works
Here is the code:
#include <stdio.h>
int main(void) {
int N, a, n;
int x=0;
int t=0;
printf("1"); //Check
scanf("%d", &N);
printf("2"); //Check
int nums[N];
int i;
printf("%d", &N); //Check
for (i=0; i<N; i++)
{
scanf("%d", &nums[i]);
t+=nums[i];
if (nums[i] > x) x=nums[i];
if (i=0 || nums[i] < n) n = nums[i];
}
a = t/N;
printf("Number Processed: \t%d\n", &N);
printf("Maximum: \t%d\n", &x);
printf("Minimum: \t%d\n", &n);
printf("Total: \t%d\n", &t);
printf("Average: \t%d\n", &a);
}
The way i run the program is
gcc -lab16
./a.out <in1
where in1 is text and has the numbers
7
6
-30
90
3903
-934
443
445
Thanks for your time.
if (i=0 || nums[i] < n) n = nums[i];
you are assigning i = 0, so the loop never realy advances! You probably wanted i == 0. This is causing the infinite loop.
Other issue: int nums[N]; - if you want an array of dynamic [determined in run-time] size, you will probably need to malloc() it.
Update: note that int nums[N] is valid in C99, so if your assigment is assuming C99 you should not worry about this issue. Otherwise - malloc() will be needed:
int* nums = (int*) malloc(sizeof(int) * N)
And don't forget to free(nums) before the program ends, or you will get memory leak.
if (i=0 || nums[i] < n) n = nums[i];
This is the culprit. You are making an assignment i=0 when you should do a comparison : i==0
Your loop goes to infinity because everytime you are i to 0.
Moreover, the code you gave us, gave me an error, because you were creating new variables during runtime.
#include <stdio.h>
#include "stdlib.h"
int main(void) {
int N, a, n;
int x=0;
int t=0;
int i;
int *nums;
printf("1"); //Check
scanf("%d", &N);
printf("2"); //Check
nums = malloc(N*sizeof(int));
....
There are numerous problems with this code.
You mistook assignment for comparison:
i=0
sets i to zero. You probably meant
i==0
which checks whether i is equal to zero.
You should check the value returned by scanf(). When data read by scanf() doesn't fit the format you specified it leaves the data in the buffer and the next call to scanf() sees the same data again.
The reason that the first printf() doesn't print anything is most likely that you are not printing any newline. Note that on some output devices like terminals output is line-buffered.
You are passing a pointer to a variable to printf(), but your format specifies %d. You probably meant the variable itself, not a pointer to it.
Also, if you need an array of length dependent on a value known only at runtime, you need to allocate it on the heap, e.g. using malloc().

Resources