Segmentation fault in c dealing with scanf - c

I'm writing a program that requires me to do a union of two arrays. Here is my code so far.
I get Segmentation fault as an error after I enter set A.
#include <stdio.h>
void Union(int a[], int b[], int set1, int set2)
{
int u[20], i, j, unionIndex=0,trigger;
for(i=0; i<set1; i++)
{
u[unionIndex] = a[i];
unionIndex++;
}
for(i=0; i<set2; i++)
{
trigger=0;
for(j =0; j<set1; j++)
{
if(b[i] == u[j])
{
trigger =1;
break;
}
}
if(trigger =0)
{
u[unionIndex]=b[i];
unionIndex++;
}
}
for(i=0;i<unionIndex;unionIndex++)
{
printf(" %d",u[i]);
}
}
int main(void) {
int N=0;
int M=0;
int i;
int j;
printf("Please enter the number of elements in set A: ");
scanf("%d",N );
int a[N];
printf("Enter the numbers in set: ");
for(i=0;i<N;i++)
{
scanf("%d",&a[i]);
}
printf("Please enter the number of elements in set B: ");
scanf("%d",M );
int b[M];
printf("Enter the numbers in set: ");
for(j=0;i<M;i++)
{
scanf("%d",&b[i]);
}
Union(a,b,N,M);
return 0;
}
I'm pretty sure the issue has something to do with arrays because the program will compile but i get the error right after the user enters set A. I'm a beginner at C but I know a lot more about Java, so I'm thinking this has something to do with memory allocation. I'm not really sure how to solve the issue, so if you could point me in the right direction that would be helpful.

You need to pass the address of the variable to scanf()
Change
printf("Please enter the number of elements in set A: ");
scanf("%d",N );
to
printf("Please enter the number of elements in set A: ");
scanf("%d", &N);
Same goes for other place
printf("Please enter the number of elements in set B: ");
scanf("%d", &M);
There is another possible mistake
Its here
for(j =0; j<set1; j++)
{
if(b[i] == u[j])
In this set1 is equal to N, so j will go from 0 to N-1. And array u[] has only 20 elements. There is a possibility of array access out of bound if some user enter value more then 20 for N.

The problem, as I see it is in
scanf("%d",N );
and
scanf("%d",M );
It invokes undefined behavior as scanf() needs the argument to a format specifier to be a pointer to the type.
Just to clarify, you're essentially passing the address as 0 (value of the variable), which is not a valid addres, anyway.
You need to pass the address there, like
scanf("%d", &N );
and
scanf("%d", &M );
That said, in your Union() function, you're using a user-defined value to limit the for loop, against a constant value 20. In case the user input is more than 20, you'll be overrunning the memory which invokes undefined behavior.

The reason you're getting the segmentation fault is because of how you're calling scanf when reading in N and M. The %d format specifier for scanf expects an int *, i.e. the address of an int, but you're passing in an int. This is undefined behavior.
So you can fix them like this:
scanf("%d",&N );
....
scanf("%d",&M );
Some addtional bugs:
When looping to read in the values for b:
for(j=0;i<M;i++)
{
scanf("%d",&b[i]);
}
You have the wrong loop indexes:
for(j=0;j<M;j++)
{
scanf("%d",&b[j]);
}
When checking trigger:
if(trigger =0)
This is an assignment, not a comparison:
if(trigger == 0)
When looping to print out u:
for(i=0;i<unionIndex;unionIndex++)
You're incrementing the wrong variable:
for(i=0;i<unionIndex;i++)
Finally, u need to have a length of at least set1 + set2, otherwise you risk writing off the end of the array:
int u[set1+set2];
Fix those and you should get the desired results.

Related

Getting unexpected output in C while accessing array. Getting mostly 0 as output

This is my code
#include<stdio.h>
int main()
{
int n,a[n],op;
printf("Enter size of the array\n");
scanf("%d",&n);
printf("Enter the array elements\n");
for(int i=0;i<n;i++)
{
scanf("%d",&a[n]);
}
printf("Select array element to display from 1 to %d\n",n);
scanf("%d",&op);
if(op-1>=0&&op-1<n)
{
printf("Element is %d\n",a[op-1]);
}
else
{
printf("Invalid Entry\n");
}
return 0;
}
Output
Enter size of the array
5
Enter the array elements
2
5
6
1
5
Select array element to display from 1 to 5
2
Element is 0
Why is this happening? I couldn't figure this out
Consider your code:
int n,a[n],op;
Given that the value of n is undefined at this point, the variable length array (VLA) created by a[n] will be of some arbitrary size. C doesn't magically reach back in time from the point where you request a value of n and adjust the array size :-)
You need to create the VLA after you've set the value of n, reorganising your code at the start of main with something like this:
int n,op;
printf("Enter size of the array\n");
scanf("%d",&n);
int a[n];
That way, n will be a known value when you use it to create the VLA.
Additionally, your scanf("%d",&a[n]); is undefined behaviour because n will always be beyond the end of the array (which has indexes 0 through n-1 inclusive). You should be using i as the index there.
There are other logic issues such as checking that the scanf succeeded and that you didn't enter a non-positive number but that's usually okay for educational code (assuming that's what this is). As you develop as a coder, you will naturally begin to think of these possibilities and harden your code accordingly.
By way of example, this is a better way to enter n, although you could recover from non-numeric data as an optional extra (see here for a nifty line input solution in C):
int n = -1;
while (n < 1) {
printf("Enter array size (positive integer): ");
if (scanf("%d", &n) != 1) {
puts("\nERROR: non-numeric");
exit(1);
}
}
scanf("%d",&a[n]);
should be scanf("%d",&a[i]);
The error is in this part of your code:
int n,a[n],op;
// int n is not defined as anything so it is a garbage value
// you specify the size of the array to be n
// which allocates an undefined size for the array
Also in your first loop you reassign &a[n], which is undefined since it goes beyond the size of the array and even if it were valid it would just reassign a single element, it should be &a[i].
to fix it read the value of n before defining array 'a'. The changes i made are down below:
#include<stdio.h>
int main()
{
int n; // change
printf("Enter size of the array\n");
scanf("%d",&n);
int a[n],op; // change
printf("Enter the array elements\n");
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]); // change
}
printf("Select array element to display from 1 to %d\n",n);
scanf("%d",&op);
if(op-1>=0&&op-1<n)
{
printf("Element is %d\n",a[op-1]);
}
else
{
printf("Invalid Entry\n");
}
return 0;
}

Could someone please point out the error in my code

#include<stdio.h>
int main()
{
setbuf(stdout,NULL);
int p,q,r,s,a[p][q],b[r][s],i,j,k,u,v,res[u][v],sum=0;
printf("Enter the number of rows and columns of the 1st matrix: ");
scanf ("%d%d",&p,&q);
printf("Enter the number of rows and columns of the 2nd matrix: ");
scanf ("%d%d",&r,&s);
printf("Enter the elements of matrix1: ");
u=p;
v=s;
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the elements of matrix2: ");
for(i=0;i<r;i++)
{
for(j=0;j<s;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<p;i++)
{
for(j=0;j<s;j++)
{
for(k=0;k<r;k++)
{
sum+=a[i][k]*b[k][j];
}
res[i][j]=sum;
sum=0;
}
}
printf("The resultant matrix is: ");
for(i=0;i<p;i++)
{
for(j=0;j<s;j++)
{
printf("%d\t",res[i][j]);
}
printf("\n");
}
return 0;
}
**I'm trying to write a program to perform Matrix Multiplication. The code isn't getting executed...its just terminating and I really cant find the error. When I tried running it online I got ''Bus error(Code Dumped)error 135"...but in my system the programs just terminating without an error. Please help me find the mistake or concept I'm missing here.. **
In the code
int p,q,r,s,a[p][q],b[r][s],i,j,k,u,v,res[u][v],sum=0;
you are using the values of p, q, r, s, u and v uninitialized. As they have automatic storage (local scope) and the type int can have trap representation, and the variables u and v never have their address taken, it'll invoke undefined behaviour. Even for the other variables other than u and v, the values will be indeterminate, resulting in practically invalid code.
To resolve the problem, define the VLAs after you scan the values into the respective variables to be used as array dimension.

C program displays garbage value while taking user input using scanf

I was writing a C program to find inversions in an array. The program compiles smoothly but as soon as I run it, it displays a garbage value where I take the array as a input. The program is given below:
#include <stdio.h>
#include <stdlib.h>
int checkInversions(int arr[], int n) {
int i, j, inverse_count = 0;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
inverse_count++;
}
}
}
return inverse_count;
}
int main() {
int arr[10], i, n;
printf("Enter the elements of the array: %d");
for (i = 0; i <= 10; i++) {
scanf("%d", &arr[i]);
}
n = sizeof(arr) / sizeof(arr[0]);
printf("\n The inverse is: %d", checkInversions(arr, n));
return 0;
}
Now, when the statement Enter the elements of the array: is displayed, just beside that is a garbage value like 623089. I am able to take the input but the result is not correct. What is the cause of this? Any help in this regard will be appreciated.
You are calling printf with a format specifier for %d and nothing passed to satisfy the variable expected by the format string. This is undefined behavior.
What you meant to do was merely:
printf("Enter the elements of the array: ");
Also, since arr has 10 elements, you iterate through it as such:
for(i = 0; i < 10; i++)
You don't need to use sizeof to determine the size of the array since you already know it; it's 10.
I think you are missing the variable that should populate the %d on the printf.
Try taking out the %d on the printf call so it ends up like:
printf("Enter the elements of the array: ");
Or assign the corresponding variable to display with that "%d", like this:
printf("Enter the elements of the array: %d", variable);
Check if that helps!
Your problem is printf("Enter the elements of the array: %d");. You tell the program that you want to print an integer, but you do not specify which integer that is. Remove the %d and the garbage value will be gone, like this: printf("Enter the elements of the array: ");

wrong print in coding c using pointer and array without no warning

int main()
{
int i, Quant, *Qsize1[4];
char *size1[4], size[5];
for(i=0; i<3; i++)
{
printf("Select Size : (S, M, L, XL) ");
scanf("%s",size);
size1[i]=size;
printf("How much quantity for this size? : ");
scanf("%d",Quant);
Qsize1[i]=Quant;
}
for(i=0; i<3; i++)
{
printf("\nSize %s : %d",size1[i], Qsize1[i]);
}
return 0;
}
example of print that i want is = Size L : 25
but when i print the it will print the last size i enter.
also the quantity of that size is wrong.
All the sizes are the same when you print them because you're reading all of them to the same character array named size. Each iteration overrides the previous size, and then you end up with size1[0], size1[1], size1[2] all point to the last size.
Quantity is wrong because you should pass scanf the address of the integer: scanf("%d", &Quant);
Also, as mentioned in the comments, you should fix how you read size itself. See this question about how to do it properly.

Scan and sum using array in C

I'm trying to write a simple program that'll prompt the user to enter N numbers, store them in an array, then just sum them all up
I understand I can just do this with a recursion but I'm trying to learn how array works
Example:
1 (hit enter)
2 (hit enter)
...
10 (hit enter)
Expected output: 55
#include <stdio.h>
int main (void){
int n;
int a[n];
int counter;
printf("How many numbers do you want to enter? \n");
scanf("%d", &n);
printf("OK! now enter your number: \n");
for (int i = 0; i <= n; i++){
scanf("%d", &a[i]);
counter =+ a[i];
}
printf("The answer is: %d\n", counter);
return 0;
}
Right now there's no error message, no output, just the standard windows error message
"scanner.exe has stopped working..."
I'm using Win8 and GCC compiler
First of all, you can't create an static array without first knowing its size. You first need to ask the user for the "n" variable and then declare your array.
You also need to explicitly initialize your counter variable to be zero before you start counting. In C, variables don't default to 0 when you declare them.
The operator "=+" doesn't exist AKAIK, change it to "+=".
Last but not least, the limit in your loops is a little off, you're asking for 11 values ;)
(I edited this post, I was wrong about only asking for 9 values. I tend to confuse that sort of stuff)
#include <stdio.h>
int main (void){
int n;
int counter = 0;
printf("How many numbers do you want to enter? \n");
scanf("%d", &n);
int a[n];
printf("OK! now enter your number: \n");
for (int i = 0; i < n; i++){
scanf("%d", &a[i]);
counter += a[i];
}
printf("The answer is: %d\n", counter);
return 0;
}
You are using variable length arrays. At run time the value of n must be known. Place the declaration
int a[n];
after taking input for n, i.e, after scanf("%d", &n); and initialize counter to zero before using it otherwise you will get garbage value (because of undefined behavior).
Also change the for loop condition from i <= n to i < n.
After this line:
int n;
What do you think the value of n is?
Now go to the next line:
int a[n];
How big is this array?
Can you access it properly?

Resources