Why do I get segmentation fault in C? [duplicate] - c

This question already has answers here:
segmentation fault using scanf with integer
(2 answers)
Closed 7 years ago.
Why this question is not duplicate?
The problem can't be at scanf, as it is given by the hackerrank and I can't modify the code! Also, test cases are automated, given by hackerrank. We can trust them with input reading. There is some bug in my logic of finding two elements in array, couldn't find it though :|
Note: I can't modify main method, as mentioned earlier. Re-iterating it. Why can't I modify? It is because the method is given by the portal. I can't change it. It reads the input and calls my method through some automated scripts, I've no control over it. So, please don't tell me to modify main method.
I was trying some practice problems in hackerrank in C language and some of the test cases started throwing Segmentation fault for following problem. I've tried understanding it for more than 2 hours now and couldn't think of any test case which will throw segmentation fault. I'm stuck :|
Problem statement:
Given an array and a number. Find if there are 2 elements in array, whose sum is equal to given number. If number are present return 1, otherwise 0.
pretty easy, huh? I thought the same and coded it as follows,
int compFunc (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int isSumPossible(int a[], int L, int N ){
/*L: Length of the array */
if(a==NULL) return 0;
if(L<=1) return 0;
int left=0, right=L-1;
qsort(a,L,sizeof(int),compFunc);
while(left<right)
{
if(a[left]+a[right]==N) return 1;
else if(a[left]+a[right]<N) left++;
else right--;
}
return 0;
}
int main() //given by hackerrank, I can't modify main method
{
int N; scanf("%d", &N); //fixed &N - it was correctly given in code, I missed it while typing it here.
int a[100004], i=0;
//read input into array a, based on N
int x;scanf("%d", &x); //fixed &x - it was correctly given in code, I missed it while typing it here.
printf("%d", isSumPossible(a,N,x));
}
Please assume all the header files required are included. Now, when I ran the code, most of the test cases passed and for some test cases they showed Segmentation fault. Unfortunately test cases aren't visible to me :|. I've gone through my code more than 10 times & I don't understand in which scenario I would get Segmentaion fault. Can anyone help me in understand which scenario am I missing in my code and why do I see segmentation fault?

The problem is in the scanfs in the main part of the code.
If you look at documentation the function description even says:
Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments.
This means you must give it a memory address to write data to. By adding & to both of your integer variables in your main the problem is solved.
int main()
{
int N; scanf("%d", &N);
int a[100004], i=0;
//read input into array a, based on N
int x;scanf("%d", &x);
printf("%d", isSumPossible(a,N,x));
}

Related

Runtime Error with Two Dimensional Arrays

Trying to solve this problem from Hackerrank. The problem itself is conceptually simple, basically finding the coordinates of a point by a simple arithmetic operation.
But the code requires us to print out multiple solutions after taking all the inputs, for which I am using a two-dimensional nx2 array. n is taken as the input from the user. Unfortunately, whenever n>=3, the hackerrank interface just does not give any output at all and I get wrong solutions. I tried to run the same code in my local IDE (CodeBlock for windows). There, when n>=3, the execution stops as the .exe file encounters some runtime error. So is it impossible to use a big matrix in those interfaces?
int main() {
unsigned int i=0, n;
scanf("%d", &n);
int **array=malloc(2*sizeof(int*));
for(;i<2;i++) *(array+i)=malloc(n*sizeof(int));
for(i=0;i<n;i++){/*Takes input via scanf*/
/* Calculate and store the result in **(array+i), *(*(array+i)+1))*/
}
for(i=0;i<n;i++) printf("%d %d\n", **(array+i), *(*(array+i)+1));
/*Prints the outputs. This is where the runtime error happens*/
return EXIT_SUCCESS;
}

Segmentation error in c program

I am getting segmentation error when trying to do this simple c sorting program
I am a novice in C language . And can you please explain me why i am getting segmentation error
#include<stdio.h>
int main(void)
{
int prev,next,result,total_number;
int i,j=1,b;
int a[i];
printf("Number of values to be entered");
scanf("%d",total_number);
printf(" enter the values \n");
for(i=0;i<=total_number-1;i++)
{
printf(" enter the values \n");
scanf("%d",a[i]);
}
for(i=0;i<=total_number-2;i++)
{
for(j=1;j<=total_number-1;j++)
{
if(a[i]>a[j])
{
b=a[i];
a[i]=a[j];
a[j]=b;
}
else
{
break;
}
}
}
for(i=0;i<total_number-1;i++)
{
printf("The numbers are %d",a[i]);
}
}
The segmentation fault is caused by this line:
scanf("%d",total_number);
You're missing the address of (&) operator, it should be like this:
scanf("%d",&total_number);
The operator is also missing in this line:
scanf("%d",a[i]);
You can find more details on scanf in the glibc manual:
Another area of difference between scanf and printf is that you must remember to supply pointers rather than immediate values as the optional arguments to scanf; the values that are read are stored in the objects that the pointers point to. Even experienced programmers tend to forget this occasionally, so if your program is getting strange errors that seem to be related to scanf, you might want to double-check this.
But there are other subtle errors in your code, too: the fact the int i in array[i] is not initialized leads to undefined behaviour i.e., anything could happen. You can use malloc to allocate space for the array, but a simple reordering could be enough:
scanf("%d",&total_number);
int a[total_number];
Uses user input to allocate the array.
Lastly, it seems like you're trying to implement an insertion sort algorithm, but the logic is slightly flawed: even correcting the bugs in the code the input
1 3 5 0
gets "ordered" to
1 5 3 0
But I don't know what you were trying to implement. In case you were actually trying to implement insertion sort, you could use the pseucode from the insertion sort wiki article to get an idea of what's missing in your implementation.
int a[i]; is creating an array of arbitrary size since i is not initialized.
Instead, you can dynamically create the equivalent of an array of int once you know total_number.
int* a;
. . . snip . . .
/* once you know total_number */
a = (int*) malloc(total_number, sizeof(int));
/* you can use a with array notation as long as you stay in bounds */
a[i] = something;
/* don't forget to free a when you are done */
free(a);

C: segmentation fault due to not freeing memory in somewhere else. how to free memory

I have a function as Follows:
double **E_min;
int *D_K;
double *prob;
char checker[] = "yes";
while(!strcmp(checker,"yes")){
.
.
.
E[I_indice][t] = ProcurementCost(Q[t+1][I_indice], c, k) + h*fmax(0,I[t])
+ p*fmin(0,I[t])
+ CalculateSigma(d_max, I_indice+Qt_DP, E_min, D_K, prob, t+1, Num_DK);
.
.
.
free(E_min)
free(D_K)
free(prob)
printf("Do you want to check another forecast? (yes/no)\n");
scanf("%s", &checker[0]);
} // this is for while loop
I have my segmentation fault in CalculateSigma function.
here is my calculate sigma function:
double CalculateSigma( int D_max, int insideSum, double **Emin,
int *D_K, double *probability, int insideTIME, int num_DK)
{
int counter;
double Sigma = 0;
for (counter = 0; counter < num_DK; counter++ )
{
Sigma += probability[counter]* Emin[insideSum- D_K[counter]][insideTIME];
}
return Sigma;
}
So here is the question.
When I run this program for the first time, it runs completely without any issue. but when it asks that if I want to give another number, it will give me a segmentation fault after getting into CalculateSigma function. I think the reason is the three pointers that I have in the function which are : Emin, D_K, Probability are not the same as my pointers in the main loop. so I have to free them. but if I free them I get a seg fault from the begining, because they are also somehow related.
So i got completely confused here. can someone tell me what should i do??
thanks
There are other issues with the code and/or it is incomplete. But, first things first.
Why do you have ?
free(E_min)
free(D_K)
free(prob)
if you intend to reuse the variables in the next loop iteration. Also, I don't see where they were first allocated. These are basic questions to be resolved, before proceeding further.

Why does the program crash when the function is called in c?

I recently had to create a program where the user enters a certain integer N. After that, my int main() had to call a seperate function, int getNextFibonacciNumber(void), which calculates the Nth term in the fibonacci sequence and then prints it. When I compile the code, Vode::Blocks says that there aren't any errors or warnings. This said, when I try to run the program, it automatically crashes. I have read it and re-read it but I am not able to see where it all went wrong. Would anyone be able to shed some light on this mysery? Thank you very much! When the program crashes, it says: filename.exe has stopped working. A problem caused the program to stop working correctly. Windows will close the program and notify you if a solutions is available. However, when the code is compiled in Code::Blocks, everything is fine.
#include <stdio.h>
#include <stdlib.h>
int getNextFibonacciNumber(void);
int main()
{
int N, fibonacci[N];
printf("Enter a positive integer:");
scanf("%d", &N);
printf("The %d th term in the Fibonacci sequence is: %d", N, getNextFibonacciNumber());
}
int getNextFibonacciNumber()
{
int N, i, fibonacci[N];
fibonacci[0] = 0;
fibonacci[1] = 1;
for(i = 2; i < N+1; i++)
{
fibonacci[i] = fibonacci[i-1] + fibonacci[i-2];
}
return(fibonacci[N-1]);
}
The problem is, that this
int main()
{
int N, fibonacci[N];
invokes undefined behavior. N is not initialized, but used as a C99 variable length array size specifier. Reading a value from a uninitialized variable invokes UB.
To fix this issue you have to write
int main()
{
int N;
printf("Enter a positive integer:");
scanf("%d", &N);
int fibonacci[N];
However there's another problem, namely that you have the same UB causing construct in getNextFibonacciNumber. You have to fix that to. Also the number entered into N is not "communicated" to getNextFibonacciNumber, so I highly doubt that this program worked at all, even if it didn't crash.
Code::Blocks (or rather the compiler Code::Blocks calls) only checks if you have written "legal" c code. It does not (and can not) check if your program does what you want, if your program will exit at any point (or simply run forever), if your program causes errors and crashs and stuff like this.
When you say
int N, fibonacci[N];
I guess you want to create an integer N and an array of the same size. However right now you create an integer N (that has some "random" value, presumably 0) and an array of the FIXED size N.
If you change N late on in your program this does not affect the size of your array "fibonacci" in any way. So if your N was by chance 0 at the beginning of your program than you have created an array of size 0. Even if you read a value (say 5) from the console input. Trying to read and write to this array causes problems.
Moving the part
int fibonacci[N];
below your "scanf" line will fix this problem. At this point N is initialized (and not some random number).
Also be aware that the variable N in the main function
int main()
has no connection at all to the N variable in your function
int getNextFibonacciNumber()
The second N is a newly created variable (again set to some "random" value). If you want to pass data from one function to another you should do it by passing it as an argument in brackets:
int getNextFibonacciNumber( int N)

Get exception error in C when trying to loop array

//Program Written By: Andre Chitsaz-zadeh
//Program Written On: 10/7/12
//Program calculates book cost for multiple book orders. Program written using multiple functions.`
#include <stdio.h>
#define SIZE 5
void inputData();
int main ()
{
inputData();
}
void inputData()
{
int i = 0;
int costs[5];
printf( "\nPlease enter five products costs.\n" );
while(i < 5)
{
scanf("%d", costs[i]);
i = i + 1;
}
}
Why do I get in exception error? The program looks simple enough! It compiles without problems but as soon as I input a number it says that "this program has stopped working". Thanks!!
scanf("%d", costs[i]);
Should be:
scanf("%d", &costs[i]);// &cost[i] gets the address of the memory location you want to fill.
It should be
while(i < 5) {
scanf("%d", &costs[i]);
i = i + 1;
}
a little typo I assume, anyway you need to provide the address of the element of the array you want to scan the integer into.
I would guess it's this line:
scanf("%d", costs[i]);
It should be:
scanf("%d", &costs[i]);
scanf needs a pointer to the variable in which it should put the read result.
This looks like a homework question, judging by the comment about the program have multiple functions. If functions are new, then pointers have probably not been covered yet. In that case, read my explanation as:
scanf needs a & before the variable in which it should put the read result. You'll learn why in a few weeks.
I think you'll need to change you scanf line to
scanf("%d", &costs[i]);
You need to pass the address of the int to have user input written to it. Your current code passes the value of costs[i]. This is undefined so will point to an unpredictable, and probably not writeable, location in memory.

Resources