Segmentation fault in C when using arrays - c

When this code is run, it shows a segmentation fault. But when address(LessThan)countarray is changed into address<=countarray, it works. I just want it to print one less array but it doesnt let me.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,check,divisor,countarray,address;
int pn[100];
for (n=2;n<100;n++){
for (divisor=2;divisor<n;divisor++){
if ((n/divisor)*divisor==n) //if (n is not a prime number)
check++;
}
if (check==0){ //if its a prime number,
pn[countarray]=n;
countarray++;
}
check=0;
}
for (address=0;address<countarray;address++)
printf("address for %d is %d and ",pn[address],address);
return 0;
}

there is no problem with condition address<countarray, you should initialize check & countarray variable.
int n,check=0,divisor,countarray=0,address;

Related

find sum of infinite series.Why does it issue a zero amount?

You need to find the sums of an infinite series with a given accuracy.(the picture with the task is given as a link)
the program constantly counts the zero amount. I don't understand what my mistake is
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int i;
int n =1;
double E,x,q;
double sum = 0;
scanf ("%f",&E) ;
scanf ("%f",&x) ;
q=pow(x,3)/6;
while(fabs(q)>=E){
if (n/2==0) {
sum=sum+q;
}
else {
sum=sum-q;
}
q=(q*pow(x,2))/(n+3);
n=n+1;
}
printf("%f",sum);
return 0;
}
It will never going to enter to that if statement. You are letting n=1 and it will be always 1, and u are doing n=n+1 in the else.

Can't find the error in minimum difference between two numbers on array in C

So I'm really new to programming. I need to write a program that, if I give it any array of integers, it'll be able to find the two numbers closest to each other, and then give the difference between those two numbers. Also, the first number must be the number of integers that are going to be in the array.
So for example, I give it 3 1 4 8. The first 3 means that there will be three integers, so it must find the closest two numbers between those three. In this case, it's 4 - 1 = 3, so the output should be 3, but when I write it it gives me 16.
This is what I have, and I don't know what's wrong:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i;
printf("Write numbers here\n");
scanf("%d", &n);
int st[n];
for(i=0;i<n;i++)
scanf("%d",&st[i]);
int a, b, str[n*n], minimum, c;
/* here I'll make a new array, and its elements will be all the
differences between all the elements of the previous one */
for(a=0;a<n;a++)
for(b=0+a*n;b<n;b++) {
if(st[b-a*n]==st[a])
str[b]=32000;
else
str[b]=abs(st[b-a*n]-st[a]);
}
// here I'll find the smallest element on the last made array
minimum = str[0];
for(c=0;c<n*n;c++)
{
if(str[c]<minimum);
{
minimum=str[c];
}
}
printf("%d", minimum);
return 0;
}
Edit: I tried to fix it with your answers but it still doesn't work.
New code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i;
printf("Write numbers here\n");
scanf("%d", &n);
int st[n];
for(i=0;i<n;i++)
scanf("%d",&st[i]);
int a, b, minimum;
minimum = st[0];
for(a=0;a<n;a++)
for(b=0;b<n;b++) {
if((st[b] != st[a]) && (abs(st[b]-st[a]))<minimum)
minimum = abs(st[b]-st[a]);
}
printf("%d", minimum);
return 0;
}
Edit 2: Ok, I fixed it now. Thanks a lot ^^
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main() {
int n, i;
printf("write numbers here\n");
scanf("%d", &n);
int st[n];
for(i=0;i<n;i++)
scanf("%d",&st[i]);
int a, b, minimum;
minimum = INT_MAX;
for(a=0;a<n;a++)
for(b=a+1;b<n;b++) {
if((abs(st[b]-st[a]))<minimum)
minimum = abs(st[b]-st[a]);
}
printf("%d", minimum);
return 0;
}

Why am i getting segmentation fault in C code?

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
int t,i,rem,l[i],b[i];
scanf("%d",&t);
for (i=0;i<t;i++)
{
scanf("%d %d",&l[i],&b[i]);
}
for (i=0;i<t;i++)
{
if (l[i] > b[i])
{
rem = l[i]/b[i];
rem +=1;
printf("%d \n",rem);
}
else if (l[i] > b[i])
{
rem = b[i]/l[i];
rem +=1;
printf("%d \n",rem);
}
else
{
printf("1 \n");
}
}
return 0;
}
Hi my code is getting compiled but not running due to a segmentation fault. Please help me in figuring out whether its become of some memory issue or scanf statements
Here:
int t,i,rem,l[i],b[i];
i is not initialized and you are creating arrays of size i (what's the value of i currently?). Arrays are of fixed size and it won't change when the value of i changes.
Fix the problem by changing
int t,i,rem,l[i],b[i];
to
int t, i, rem;
and add
int l[t], b[t]; /* You want arrays of `t` size */
after
scanf("%d",&t);
so that t gets initialized when the VLAs (Variable Length Arrays) are created.

Simple C Program Error..Can't resolve it

I'm trying to generate random numbers in C using srand(). I want to generate numbers from 1 to 25 without duplication, So i have implemented the following program.
#include <stdio.h>
#include <time.h>
int main()
{
int i=0,n,a[25]={0},b[25]={0},cntr=0;
srand(time(NULL));
while(cntr!=25)
{
n=rand()%26;
if(n!=9)
{
if(a[n]!=1)
{
a[n]=1;
printf("%d ",n);
b[i]=n;
printf("%d\n",b[i]);
cntr++;
i++;
}
}
}
for(i=0;i<25;i++)
{
printf("%d ",b[i]);
}
return 0;
}
Now there is a weird problem. When i print the array b inside the loop where the random number is generated it prints correct numbers. But when i print it outside the loop the first element of the array b changes to 1 and i get duplicate value of 1 in the random numbers. I would appreciate if anyone can help to find error in the program.
Here is the link to ideone where i have provided the output of the program : Ideone Link
You declare a[25] but you access any of 26 elements since n=rand()%26;, so declare instead
int i=0,n,a[26]={0},b[26]={0},cntr=0;
BTW, compile with all warnings and debug info (e.g. gcc -Wall -Wextra -g). Then use the debugger (gdb). A watchpoint would have helped.
there are several little oops in the posted code.
the following corrects those oops
#include <stdio.h>
#include <stdlib.h> // srand(), rand()
#include <time.h> // time()
int main()
{
int i=0; // generated number counter
int n; // generated number
int a[25]={0}; // tracks which numbers have been generated
int b[25]={0}; // random array of numbers 1...25
srand(time(NULL));
while(i<25) // correct loop termination
{
n=rand()%25+1; // yields 0...24 +1 gives 1...25
if(a[n]!=1)
{ // then, number not previously generated
a[n]=1; // indicate number generated
printf("%d ",n); // echo number
// save number in current location in array 'b'
b[i]=n;
printf("%d\n",b[i]); // echo number again
i++; // step offset into array 'b' (and loop counter)
} // end if
} // end while
for(i=0;i<25;i++)
{
printf("%d ",b[i]);
} // end for
return 0;
} // end function: main

Why do I get the error "Segmentation fault (core dumped)"?

I just started with C programming and I'm making a program that calculates a specific amount of Fibonacci numbers. It works fine, except that I get the error "Segmentation fault (core dumped)". What's wrong with my code?
#include <stdio.h>
int main() {
int max;
long long int fiNum[] = {1, 1};
printf("How many numbers do you want to get? ");
scanf("%d", &max);
int i = 1;
long long int x;
while ( i < max ) {
x = fiNum[i] + fiNum[i-1];
printf("%lld ", x);
i++;
fiNum[i] = x;
}
printf("\nDone!\n");
return 0;
}
When I ask for let's say 10 numbers the output is:
2 3 5 8 13 21 34 55 89
Done!
Segmentation fault (core dumped)
I'm using Linux (Ubuntu) btw.
Thanks in advance.
You're going out-of-bound accessing the static array fileNum for which only 2 elements are allocated.
Hence you're the victim of undefined behavior. Anything could happen but in your case it's crashing at the end.
If you want to store the generated fibonacci numbers then better dynamically allocate the array after getting the input from the user.
since you said that you are a C beginner, here are some tips :) :
#include <stdio.h>
int main () {
/*When you program in C, try to declare all your variables at the begining of the code*/
int max;
long long int fiNum[]={1,1}; /* malloc! It is allways the solution and the problem too, but stick with malloc
something like fiNum = malloc (n*sizeof(long int)); I never malloc a long int
so just verify if its like this...
*/
long long int x;
int i=1; /*Try to only initializes loop variables inside the loop, like: for(i=1; i< max; i++){}*/
printf("How many numbers do you want to get? ");
scanf("%d",&max);
printf("max: %d\n", max);
while (i<max) { /*Here you could use a for loop*/
printf("i value: %d\n",i);
x=fiNum[i]+fiNum[i-1];
printf("%lld ",x);
i++;
fiNum[i]=x;
}
printf("\nDone!\n");
return 0;
}
Obs.: I had run your code in my linux and because invalid access to vector position it didn't print all the numbers that I asked.
And now, the fixed code:
#include <stdio.h>
#include <stdlib.h>
int main () {
int max;
int i;
long long int *fiNum;
printf("How many numbers do you want to get? ");
scanf("%d",&max);
fiNum = malloc(max*sizeof(long int));
fiNum[0] = 1;
fiNum[1] = 1;
for (i = 1; i < max-1; i++)
fiNum[i+1] = fiNum[i]+fiNum[i-1];
for (i = 0; i < max; i++)
printf("fi[%d]: %d\n", i+1, fiNum[i]);
printf ("\nDone!\n");
return 0;
}

Resources