How to avoid segmentation fault in C when the array is defined? - c

I have an array A1[ ]={1,0,1,1,..'X',0,1,'X',.1,0...}, as big as 10 Megas of binary integers and some 'X' values (taken as the ASCII integer value), I am thinking to use malloc but I already have the array defined (I am just copy and paste the values before running my code). Any other suggestions on how to avoid segmentation fault? So far this the error that I am geting :(.
The code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
//int A[]={'x','x',1,0,'x',0,'x',1,1,1,...};//up to 10M values
int A[]={0,'x',1,'x',1,0,'x',0,'x','x',1,'x',0,'x','x','x','x','x','x',0};
int j;
#define n (sizeof(A)/sizeof(*A)) // bits
printf("Patt size= %d\n",n);
/*Code will be added here to make some calculations with A*/
printf("A ="); // show input
for(j=0; j<n; j++)
printf(" %d",A[j]);
return 0;
}

Related

How do I receive elements into an array using scanf?

I'm learning C programming and I've encountered a problem using scanf for initializing values into the array. In this example, 10, 32 and 20 were input as values for the array; 20 should be in grades[2] but its value is 0.
Why doesn't the program register the last value that is input?
That is the relevant code.
I'll appreciate any help in understanding what went wrong with the program.
#include <math.h>
#include <stdio.h>
#include <stdbool.h>
#define N 50
#define MaximalSTD 10
int main() {
printf("Please enter the grades of the examinees");
printf(" followed by the expected mean\n");
double grades[N], ReqMean;
int numgrade = 0;
for (int i = 0; i < N; i++) {
if (scanf("%lf", &grades[i]) == 1) {
numgrade++;
} else
break;
}
ReqMean = grades[numgrade - 1];
printf("numgrade: %d\nReqMean: %d\n", numgrade, ReqMean);
return 0;
}
printf("numgrade: %d\nReqMean: %d\n" , numgrade,ReqMean);
You are using the wrong format specifier for a double value (ReqMean in this case).
Try Instead.
printf("numgrade: %d\nReqMean: %lf\n" , numgrade,ReqMean);

code::blocks creates a .dat file but it's empty

I've been writing a code of random walk in c language. The program compiles perfectly and I can see the results in the code::blocks console. But I need to create a file .dat for import its data and make a plot of "iterations number vs the mean of the square displacement" in qtgrace.
The problem is that code::blocks creates the .dat file but it's empty. I don't know why this is happening.
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
FILE *fp;
int c,i;//c is the number of walkers and i is the iterations number
double x,r; //x is the displacement and r is a random number
double s[2000]; //array for the displacement squared
int n[10]; //array for the number of walkers
double main(){
fp=fopen("caminata.dat","w");
printf("Write the iterations number i=");
scanf("%d",&i);
printf("Write the number of walkers c=");
scanf("%d",&c);
n[10]=0;
s[2000]=0;
for (int j=0; j<c; j++){
//srand((long)time((time_t *)(NULL)));
x=0.;
for(int k=0; k<i; k++){
r=rand()/(double)RAND_MAX;
if(r<=0.5){
x=x+1;
}
if(r>0.5){
x=x-1;
}
s[k]=s[k]+x*x;//
}
}
for (int k=0; k<i; k++){//mean of the square displacement
s[k]=s[k]/c; //divided by the number of walkers
printf("\n%d %lf",k,s[k]);
fprintf(fp, "\n%d %lf",k,s[k]);
}
fclose(fp);
}
This is the plot I must obtain
Random_Walk: iterations number vs the mean of the square displacement
I see 2 times k<i in for loops but I don't see i being defined.
There is 1 chance out of 2 that value is defined to a negative value, in which case it makes sense your file is empty.

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.

Problems with arrays

I know this is going to be something of a silly slip or oversight on my behalf, but I can't get the array in this to print out correctly. When I run the code and put in my inputs, I get seemingly random numbers.
For example,
number of rooms was 1
wattage of lights was 2
hours used was 2
TV/computers was 2
The output I got was 3930804. What did I miss?
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
int room[20] = {0.0};
int i;
int rooms = 0;
char option = 0;
int lights[20];
int hrsUsed[20];
int Telly_Computer[20];
printf("Enter number of rooms");
scanf_s("%d", &rooms);
for(i=0;i<rooms;i++)
{
printf("input wattage of lights");
scanf_s("%d", (lights+i));
printf("input number of hours use/day (average)");
scanf_s("%d", (hrsUsed+i));
printf("input number of TV/Computers");
scanf_s("%d", (Telly_Computer+i));
}
printf("%d \n", lights);
}
printf("%d \n", lights);
You're printing the array directly. You need to loop over it and print the elements one at a time.
int i;
for (i = 0; i < 20; ++i)
printf("%d\n", lights[i]);
You are just printing the address of lights (and using UndefinedBehavior by the way, address must be printed with %p). You must use a loop to print out all of the contents of each array slot.
for(int i=0;i<(sizeof(lights)/sizeof(int));i++)
printf("%d\n",lights[i]);

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