Segmentaion fault in c while displaying array [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have to take 'n' lines of character array(size m), which will have numbers only, and i have to put the numbers in a 2-d integer array.
I am getting segmentation fault while displaying the integer array for second time.
int t,m,n,i,j,pix[182][182];
char ch,pixel[183];
scanf("%d",&t);
while(t--){
scanf("%d %d",&n,&m); //take n and m
for(i=0;i<n;i++){
printf("\n");
scanf("%s",pixel); //take character array
for(j=0;j<m;j++){
pix[i][j]=pixel[j]-48; //put numbers in integer array
dis[i][j]=0;
printf("%d ",pix[i][j]); //no error here
}
}
for(i=0;i<n;i++){
printf("\n");
for(j=0;j<m;j++)
printf("%d",pix[i][j]); //segmentation fault after n-1 lines are displayed
What is the problem?

Your code makes no effort to check for array boundaries. You need to check that m and n are less than 182 before proceeding. You should also use a method that protects against a buffer overrun when reading the pixel array - e.g fgets(pixel, sizeof(pixel), stdin). Otherwise, depending on the values on m and n you could have a buffer overrun with unpredictable results.
Your example also did not show the definition of the dis array, but you need to do a boundary check there as well.
Aside from that, I am guessing that your input is not laid out quite like your program expects. Performing array boundary checks and asserting as soon as they fail will help you find the discrepancy much quicker.

Related

variable inside int in c giving exceptional output [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
In below given program if I put n=0, then the program is giving right answer but if I write n instead of n=0, the program is giving me wrong answer. If I put k=10 then output is 94 but the correct answer is 55. Why it is adding additional 39?
int main(){
// program to calculate the sum of 'n' numbers
int i=1,k,n;
printf("Enter number: ");
scanf("%d",&k);
do{
n+=i;
i++;
}while(i<=k);
printf("The sum is: %d",n);
return 0;
}
Your loop is adding a value to the current value of n, but you never set the initial value of n. That means its value is indeterminate, and reading an indeterminate value (in this case when you add to it), when the variable in question never had its address taken triggers undefined behavior.
Initialize n to 0 so you have a valid starting point.
int i=1, k, n=0;

C programming - Finding the necessary number in the array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
The task is to calculate how many times a certain digit occurs in the entered sequence of numbers. The number of numbers to be entered and the number to be calculated are set by typing. Ask me if you have got question about code. The problem in finding a match with the number entered in the array.Can you give me hints or instructions, also i think about loop while but i don't know how to realize it please
The code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, b, n, c=0, arr[30];
printf("The count of numbers: ");
scanf("%d", &n);
printf("The number what is finding: ");
scanf("%d", &b);
for (i = 0; i < n; ++i)
{
scanf("%d", &arr[i]);
}
for(i=0;i < n;i++)
{
if(arr[i]=b)
{
c++;
printf("%d", c);
}
}
}
You should be compiling your code with at least some basic compilation flags. If you do, you will get a heads up that something is wrong before having to run it to find out. It saves a lot of time in the long run. Consult your compiler's documentation.
For instance, it would point out that your if condition is using an assignment (=) instead of an equality comparison (==). It should be:
if (arr[i] == b)
Also, you probably want to print out the total count at the end of the program - after the loop is finished. So move the printf("%d\n", c); after the loop. (You were also missing a newline which you probably wanted).
Also, scanf has a return value - you should check it. If the user enters invalid integers, you want to catch that and handle it properly.
Finally, since you declare your array to be of size 30, you should add a check that the desired length of the input array is no longer than that -- otherwise, you would get a buffer overflow.
Side note: please use more descriptive variable names. Not doing so often leads to confusion, especially for beginners. A small exception to this is for loop counters, like i in this case -- its perfectly fine to use a single letter. But consider b -- there is no obvious meaning; it should be something like target or to_find. Also, c could be count or total. As for n, perhaps size or length would be more suited.
if(arr[i]=b) it's wrong. x = y is an assignment but you want to do a check. To check if two elements are equal you should write if(arr[i] == b).

Program with array to find a sum in c [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I was thinking of a code to find the sum of numbers.
So i wrote bellow code :
#include <stdio.h>
#include <math.h>
int main()
{
int n,i,s=0,a[100];
printf("enter number of numbers");
scanf("%d",n);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
s=0;
for (i=1;i<=n;i++)
{s=s+a[i];}
printf("sum is%d\n",s);
}
But in the output it shows segmentation error . I.e.
So whats the mistake?
So this line:
scanf("%d",n);
should be replaced by
scanf("%d",&n);
Explanation:
scanf() reads data from stdin according to format and store data in the location pointed by next additional argument. this case, format is %d means we want to read an integer number and this integer number will be stored in the location of n. The & operator is to get the location of a variable in C.
Use this :
scanf("%d",&n);
The reason :
You MUST put & in front of the variable used in scanf. The reason why will become clear once you learn about pointers. It is easy to forget the & sign, and when you forget it your program will almost always crash when you run it.
Examples :
scanf("%d %d", &a, &b);
printf("%d %d", a, b);
As a and b above are two variable and each has their own address assigned but instead of a and b, we send the address of a and b respectively. The reason is, scanf() needs to modify values of a and b and but they are local to scanf(). So in order to reflect changes in the variable a and b of the main function, we need to pass addresses of them. We cannot simply pass them by value.
But in case of printf function as we are only going to print the values of the variables in output console, there are no changes going to be made in variable a and b’s values. So it is not required to send their addresses.

How to dynamically allocate memory in 2D array and store values? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I am trying to allocate memory in a 2D array dynamically, but I don't know what is wrong.
Error
let input is
2 2
1 2 3 4 5 6 7 8 9 ........
then program crashes
#include<stdio.h>
#include<stdlib.h>
int main()
{
int N,M;
int i,j;
scanf("%d %d",&N,&N);
int **A = (int **)malloc(N*sizeof(int *));
for(i=0;i<N;i++)
{
A[i] = (int *)malloc(M*sizeof(int));
}
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
{
scanf("%d",&A[i][j]);
}
}
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
{
printf("%d",A[i][j]);
}
}
return 0;
}
Here's your problem:
scanf("%d %d",&N,&N);
When you read in the array dimensions, you read into N twice and never read into M. As a result, the contents of M are indeterminate, and attempting to read that value invokes undefined behavior.
Fix this to input a value for M:
scanf("%d %d",&N,&M);
As i said problem is in scanning N and M variables.
Change
scanf("%d %d",&N,&N);
to
scanf("%d",&N);
scanf("%d",&M);
and you are fine.
Problem was you were reading N twice while didnt read an M which was used uninitialized.
Non-static variables (local variables) are indeterminate. Reading them prior to assigning a value results in undefined behavior.
You should free all your allocated memory
for(i=0;i<N;i++)
{
free(A[i]);
}
free(A);
and dont cast malloc()'s return value becouse
Its reduntand
Adding the cast may mask failure to include the header stdlib.h, in which the prototype for malloc is found
If the type of the pointer is changed, one must fix all code lines where malloc() was called and cast
Next time if you cannot find a bug, try to use debugger and look what exactly is happening, you can see variable values, where would you clearly see that M is uninitialized and didnt change after scanf().

print the changed variable before the calculation is done [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
in a c program, i want the variable 'count' to be printed at the beginning of the program. But the calculation for the value of 'count' is done later. How do you accomplish this?
count = 0;
printf("the value of count is : %d", count);
count = 20;
I know in this case, the output is 0. But I need 20 to be printed.
The idea of program flow is that commands are executed in a certain order. You don't expect the waiter to bring you your meal before you have told him what you want to eat - but that seems to be what you are asking.
Of course the order of lines in a file is not necessarily the order of execution: you have have a line "at the start of the file" that is executed later: for example
#include <stdio.h>
// we define the print statement here:
void printCount(count) {
printf("the count is now %d\n", count);
}
int main(void) {
int count = 20;
printCount(count); // but we don't execute it until we get here...
return 0;
}
Now your "print" statement occurs (in the file) before you assign (calculate) count - but of course they are being executed in the correct order.
afterthought
If it's a case of printing "the number of cases is n", you could of course do
printf("the number of cases is ");
cases = 5; // whatever math is needed happens here...
printf("%d\n", cases);
and the result is
the number of cases is 5
just as you wanted... this works because there was no carriage return after printing "the number of cases is" - so the number follows when you have figured it out.
edit
Reading through the question and comments one more time I think I understand what your issue is. You have a loop that counts a number of inputs (say the number of lines in a file) and want to print both the total number of cases (not known before the loop) and something about each case (discovered during the loop) but without having to loop over all the data twice. There is a way to do this, using a print buffer. If data access is really slow and looping twice would be prohibitive, this might be an option. You would want to initialize a "sufficiently large" print buffer in memory and use snprintfto create the string you need. In reality you will "loop over" the bytes in the output string twice but there is minimal performance penalty (compared to everything else). Incomplete example:
int count=0,num, sofar=0;
char buf[2000];
// assume file is opened and handle is fp
while(true){
if (fscanf(fp, "%d", &num) <1) break;
sofar+=snprintf(buf+sofar, "%d\n", 2*num); // some "math" on number for each "case"...
count++;
}
printf("There were %d lines\n", count);
printf("Here they are multiplied by two:\n");
printf("%s\n", buf);
Obviously the above is incomplete - you need to check for errors, open/close the file, etc - I am just trying to point out the principle - this way you only loop through the data (file) once but print the count before the contents.
you can't print 20. how can you print a variable before its get initialized?

Resources